From my React JS app , I need to fetch data from servers in other domains. However, I am prevented by CORS policy and not able to fetch the data.
Let us assume that my React app is running on localhost:3000 during the development. I want to make get/post call to another server running on http://myserver.com The URL through which I want to fetch the data is http://ext-server.com/data/records?name=xyz
I have installed http-proxy-middleware thru npm and using it in my react app. Created a setupProxy.js file under src folder with below content :
const { createProxyMiddleware} = require("http-proxy-middleware")
module.exports = app => {
app.use(
createProxyMiddleware('/data/records' , {
target:'http://ext-server.com',
changeOrigin: true
})
)
}
On the landing page of my react app (firstpage.js) when http://localhost:3000 is hit , I have added below piece of code to the button event that makes the get call to the http://ext-server.com
getTheData() {
let url = "http://ext-server.com/data/records?name=" + encodeURIComponent(this.state.name);
axios.get(url,
{
headers: {
"Content-Type":"application/json;charset=UTL-8",
"Access-Control-Allow-Origin": "*",
Accept: "application/json",
},
baseURL: 'http://ext-server.com'
}
).then((response) => {
console.log(response["access_token"]);
}).catch(error) => {
console.log("Error: ", error)
}).then(function () {
console.log("always call it")
});
}
In the package.json , I have added :
"proxy": "http://ext-server.com",
"homepage":"http://localhost:3000",
But I am still getting below error: Access to XMLHttpRequest at 'http://ext-server.com/data/records?name= ' from origin 'http://localhost:3000' has been blocked by CORS policy.
Is there anything that I am missing here ? what is the correct way to use this http-proxy-middleware? Any help will be very useful! Thanks
If there’s no backend/server at all and you’re only deploying a static frontend app, then http-proxy-middleware
won’t work since it needs a running Node server to intercept and forward requests. In that case, your main options are:
Request that the API you’re calling includes a response header like:
Access-Control-Allow-Origin: *
or specifically allows your website (origin). If they can do this, then it’s the cleanest fix.
If you have no control over the server, your only workaround (with no backend of your own) is to route the request through a CORS proxy. Either self-hosted (cors-anywhere) or hosted CORS proxy (Corsfix). The proxy adds the necessary CORS headers, letting your browser fetch the data without errors.
With CORS proxy, you typically add the proxy URL before your target URL
fetch("https://proxy.corsfix.com/?http://ext-server.com/data/records?name=abc");
(I am affiliated with Corsfix)