Good day to all! Using axios, I send a GET request to the API with the existing token, but this response is returned: No 'Access-Control-Allow-Origin' header is present on the requested resource. how to fix? at the moment, the application consists of the created directory using create-react-app ... I send the request in the componentDidMount method:

componentDidMount() { const instance = axios.create({ method: 'get', withCredentials: true, responseType: 'json', responseEncoding: 'utf8', }); axios.defaults.baseURL = 'https://domen/api/organization'; axios.defaults.headers.common['Authorization'] = 'MY_TOKEN'; axios.defaults.headers.post['Content-Type'] = 'application/json'; instance() .then(res => { console.log(res); }) .catch(err => { console.log(err); }); 

}

1 answer 1

In order to bypass CORS, there are two exits. (If Access-Control-Allow-Origin not allowed from the server)

The first one is the easiest: Google Access-Control-Allow-Origin extension . (After working with it, do not forget to disable it, otherwise some sites such as Youtube may not work correctly)

Download install and activate errors will not.

Second option: Set up a proxy server in a webpack .

Read how to set up a proxy server here.

  • Thanks for the suggested answer. Do I understand correctly: I need to send a request to my server at the front (even if it is local), and from there send a request to the API that is needed? (bypassing that if just ajax request at the front does not work? - staks
  • @staks on the front you have to send a request for an API that you need. I didn’t write that you should send a request to your server. I wrote that you need to set up a proxy server - Excess Suslik
  • How does setting up a webpack help solve the problem of sending it from the client? (don’t kick much I’m just learning) ... as far as I know, you can configure CORS on your server (express), is it worth it to make this layer or can it be easier? - staks pm
  • @staks read about CORS and about proxy. And until it is clear that both do not meddle about solving such problems. Good luck. - Excess Susliks