my third party axios requests works properly on local mode properly thanks to "http-proxy-middleware", but after i build and deploy it, axios requests gives homepage html as response.
setupProxy.js file
const { createProxyMiddleware } = require("http-proxy-middleware")
const cors=require("cors")
const express = require('express');
const app = express();
module.exports=app=>{
app.use(
createProxyMiddleware("/api",
{
target:"third-party-api-url",
secure:false,
changeOrigin:true
})
)
ApiFrontend.jsx file
const [apiData,setApiData]=useState("")
var data = JSON.stringify({
"MERCHANT": "****",
"MERCHANT_KEY": "*******************************"
});
var config = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
data : data
};
useEffect(()=>{
axios("/api",config)
.then(function (response) {
setApiData(response.data);
})
.catch(function (error) {
console.log(error);
});
},[])
i tried node server with express and use;
app.use(cors({
origin: API_URL,
credentials: true
}));
but it gives the same response
Related
I have created an express server in which I am implementing a graphQL request. The following block of code was taken from postman snippets of a successful request
const express = require("express"),
app = express(),
port = process.env.PORT || 4000,
cors = require("cors");
var axios = require('axios');
var data = JSON.stringify({
query: `mutation claimTask ($taskId: String!, $assignee: String) {
claimTask (taskId: $taskId, assignee: $assignee) {
id
name
taskDefinitionId
processName
creationTime
completionTime
assignee
variables {
id
name
value
previewValue
isValueTruncated
}
taskState
sortValues
isFirst
formKey
processDefinitionId
candidateGroups
}
}`,
variables: {"taskId":"22","assignee":"demo"}
});
var config = {
method: 'post',
url: 'http://[my_ip]/graphql',
headers: {
'Authorization': 'Bearer ey....',
'Content-Type': 'application/json',
'Cookie': 'TASKLIST-SESSION=..'
},
data : data
};
app.use(cors());
app.listen(port, () => console.log("Backend server live on " + port));
app.post("/api", (req, res) => {
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
res.send({ message: JSON.stringify(response.data) });
})
.catch(function (error) {
console.log(error);
res.send({ message: error });
});
})
Currently I am calling this request from a react app with a button like this:
Axios({
method: "POST",
url: "http://localhost:4000/api",
headers: {
"Content-Type": "application/json"
}
}).then(res => {
console.log(res.data.message);
});
For the next step I want to pass the variables from my react app instead of writing them directly as string to express. What is the right approach to achieve this?
I am using the express server to avoid cors related issues.
Any suggestions can be useful, thank you!
So you want to send an Axios POST from react. Something along those lines should work:
const handleSubmit = (e) => {
e.preventDefault();
const variables = {
taskId: ”22”,
userId: “demo”
};
axios.post("http://localhost:4000/api", variables).then((response) => {
console.log(response.status);
});
};
Inspired by https://blog.logrocket.com/understanding-axios-post-requests/
I'm attempting to send a complete form to back-end server (decoupled MERN application in localhost).
The request is reaching the server, but not posting to the database.
This is seen in server console...
POST /contracts 404 1.371 ms - 19
The data to be sent in form is logging in console as an object (as intended).
This is the service function making post request from the frontend to the backend ...
const BASE_URL = `${process.env.REACT_APP_BACKEND_SERVER_URL}/contracts`
export const createContract = async (formData) => {
try {
const res = await fetch(BASE_URL, {
method: 'POST',
headers: {
'content-type': 'application/json',
'Authorization': `Bearer ${tokenService.getToken()}`
},
body: JSON.stringify(formData)
})
return await res.json()
} catch (error) {
console.log(error)
throw error
}
}
this is the backend routes... (already set up as /contracts in server.js)
import { Router } from 'express'
import * as contractsCtrl from '../controllers/contracts.js'
const router = Router()
router.post('/', contractsCtrl.create)
router.get('/all', contractsCtrl.index)
export { router }
create controller function on the backend...
function create(req, res) {
console.log(req.body)
Contract.create(req.body)
.then(contract => res.json(contract))
.catch(err => res.json(err))
}
Any help you have would be appreciated!!
i got cors error and fixed it when using http-proxy-middleware according to video tutorial https://www.youtube.com/watch?v=hxyp_LkKDdk (Skip to solution: 20:08, i have followed and it is like below). everything is fine until i get the picture from the api. Did I miss something?
here's my setupProxy.js
const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
// GET Image
app.use(
"/file/",
createProxyMiddleware({
target: "https://.....",
changeOrigin: true,
})
);
};
and user.js
const loadImage = () => {
setLgShow(true);
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer abcdefghiklm");
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
method: "GET",
headers: myHeaders,
redirect: "follow",
};
fetch(`/file/${user.img_front_file_id}`, requestOptions)
.then((response) => response.text())
.then((result) => {
console.log(result);
imagRef.current = result;
console.log(JSON.parse(result));
})
.catch((error) => console.log("error", error));
};
and the binary trash (the response when I call API image)
I finally found the answer
const res = await axios({ url: `/file/${user.img_front_file_id}`, method: "GET", headers: { Authorization: "Bearer eFS3oJaQhRU1c5EajQUL", "Content-Type": "application/json", }, responseType: "blob", });
const file = new Blob([res.data], { type: "image/jpg" });
const url = URL.createObjectURL(file); imagFontRef.current = url;
setFinishFront(true); console.log(res);
This is my setupProxy.js:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = (app) => {
app.use(
'http://localhost:8000',
createProxyMiddleware({
target: 'https://my-website.com', // Should request this url
changeOrigin: true,
})
);
};
And this is how I am calling the API:
makeAPICall = (method, headers, data) => {
let url = new Url('http://localhost:8000/api/get-data');
let requestOptions = {
method,
headers,
'body': data
}
return fetch(url, requestOptions);
}
But the API calls are going to the localhost and not the one that I mentioned in the setupProxy.
I know this is not right way to call apis when using proxy middleware, and we just need to provide a simple string in app.use like '/api1'. But I am not allowed to change the urls, just want to reroute them to new api.
What am I doing wrong here?
Edit: This is how I call makeAPICall function:
headers = {
'Content-Type': 'application/json',
'Authorization': `Token ${user.auth_token}`
}
makeAPICall('POST', headers, payload).then(data => handleData(data));
I'm working with Expo React native, I'm trying to send POST request to my express server using axios
App.js - in my React
Axios({
url:'http://172.20.1.19:3001/api/tracking/locator',
method:'POST',
data:{
test:'wew'
},
config:'JSON',
headers:{
"Access-Control-Allow-Origin": "*"
}
})
.then(res=>{
console.log(res)
})
.catch(err=>{
console.log(err)
})
In node status its 200, but when console.log the response it throws an error
console.error. "There was a problem sending log message to your
development environment",
Tracking.js - Express
var express = require('express');
var cors = require('cors');
var router = express.Router()
const app = express();
const db = require('../models');
app.use(cors({origin:'http://172.20.1.19:19001'}));
router.get('/', function(req, res, next){
res.json({
data: {
test :'wew'
}
})
})
router.post('/locator', function(req,res,next){
res.json({
data:{
status:'pano mo nasabe'
}
})
})
module.exports = router
Try to use:
(this helped me)
console.log(JSON.stringify(response.data))
or
console.log(response.data)
also
console.log(JSON.stringify(response))