3

How to set up CORS Header in react front end app with webpack and axios.

I want to get a response from an API url. Do I have to set up sepparate server with let's say express, or it can be done with webpack-dev-server from the front-end application.

I get the error:

Failed to load https://api.test.io/test/res: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Vincent D'amour
  • 3,001
  • 1
  • 18
  • 33
Tadas Stasiulionis
  • 1,238
  • 3
  • 15
  • 18
  • Possible duplicate of [Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin](https://stackoverflow.com/questions/18642828/origin-http-localhost3000-is-not-allowed-by-access-control-allow-origin) – Jefree Sujit Oct 23 '17 at 16:41
  • It seems like you need to whitelist localhost for development with your API provider https://test.io – Max Gram Oct 23 '17 at 17:50
  • I opened in the browser and it says 404. Sometimes if you use API in a wrong way, you will get a CORS response. – leaf Nov 01 '19 at 02:39

2 Answers2

2

The issue is with the server, not with Axios. You need to setup your webpack devServer headers to allow CORS.

devServer: {
   headers: { 
       "Access-Control-Allow-Origin": "*",
       "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
   }
}
Vincent D'amour
  • 3,001
  • 1
  • 18
  • 33
0

You don't set CORS headers client side, they are sent automatically by the browser. You do it server side. Configure Webpack server to reply with Access-Control-Allow-Origin set to the wildcard *.

devServer: {
   headers: { 
       "Access-Control-Allow-Origin": "*"
   }
}
Scriptonomy
  • 3,641
  • 1
  • 11
  • 20