0

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

  • `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") }); }` is this in the back end? – Sohan Arafat Feb 08 '22 at 16:48
  • You cannot circumvent CORS from the client side (at least not in a browser), that is the whole point of CORS. Creating a proxy obviously works but you will run into all sorts of problems, e.g. regarding authentication, cookies, ... Does `ext-server.com` respond with proper CORS headers? – luk2302 Feb 08 '22 at 16:48
  • @Sohan Arafat no it's in front end – A.G.Progm.Enthusiast Feb 08 '22 at 16:53
  • When you do app.use('/api', myProxyMiddlewareConfig) with a properly configured proxyMiddleware, I don't expect to see any client code pointing to ext-server.com, rather it should point to /api. – James Feb 08 '22 at 16:55
  • @James can you please elaborate the change that you are suggesting here? – A.G.Progm.Enthusiast Feb 08 '22 at 17:33
  • @luk2302 Most probably ext-server.com does not respond with CORS headers. Tomorrow I might request some other ext2-server.com and not sure whether they will have CORS in their response or not. Hence using proxy – A.G.Progm.Enthusiast Feb 08 '22 at 17:37

2 Answers2

0

The CORS policy is one and only administered by the web server and its settings. To allow CORS requests it has to be implemented on server side. No chance to do it from your client application.

Basically its just a header setting (below example for NodeJS):

res.header("Access-Control-Allow-Origin", "*")

Sending that header will allow requests from every domain.

Torsten Barthel
  • 3,059
  • 1
  • 26
  • 22
0

As you can see from MDN the "Access-Control-Allow-Origin": "*" header is a response type header, this means that it should go to in your server response. Also I advise you to not use the * symbol, instead I would rather match it with the origin header in your Request.