Fetch API cannot load ... No Access-Control-Allow-Origin header

I got

  • app api deployed on heroku
  • response application deployed on heroku

the response application is trying to get data from the rest of the api using whatwg-fetch.

var header = {"Content-Type": "multipart/form-data", 'Origin': 'https://foo.bar', 'Access-Control-Request-Method': 'GET', 'Access-Control-Request-Headers': 'X-Requested-With'}; var options = {method: 'GET', credentials: 'include', headers: header}; fetch('https://myrest.api/foo', options)... 

But I can’t get any data, let's say

 Fetch API cannot load https://foo.bar. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://foo.bar' is therefore not allowed access. The response had HTTP status code 403. If an opaque response serves your needs, set the request mode to 'no-cors' to fetch the resource with CORS disabled. 

When I try to get data using curl, it works

 curl -H "Origin: https://foo.bar" \ -H "Access-Control-Request-Method: GET" \ -H "Access-Control-Request-Headers: X-Requested-With" \ -X GET --verbose https://myrest.api/foo -D header.txt 

and response header (from curl command)

 HTTP/1.1 200 Server: Cowboy Connection: keep-alive Access-Control-Allow-Origin: https://foo.bar Vary: Origin Access-Control-Allow-Credentials: true Content-Type: application/json;charset=UTF-8 Transfer-Encoding: chunked Date: Fri, 09 Dec 2016 23:52:57 GMT Via: 1.1 vegur 

Cors allowed in spring boot application via @CrossOrigin

Thanks in advance Best regards

+6
source share
1 answer

It seems that you are trying to access from one domain https://foo.bar to another domain in https: //myrest.api , and this is the cause of this error.

You have 2 options:

1) Combine these 2 applications into one domain in Heruko, React and Api applications, under https://foo.bar , for example, and this will work for you.

2) Assume the client application domain https://foo.bar to access your api domain https: //myrest.api , adding the header "Access-Control-Allow-Origin" in the api application:

 app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); next(); }); 
0
source

Source: https://habr.com/ru/post/1013050/


All Articles