Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

I got

  • a rest api deployed on heroku
  • a react app deployed on heroku

the react app tries to get data from the rest 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, it say's

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's mode to 'no-cors' 
to fetch the resource with CORS disabled.

When I try to get the data with 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 the response header (from the 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 is enabled in the spring boot application via @CrossOrigin

Thanks in advance Best Regards

like image 451
LimitX Avatar asked Dec 09 '16 23:12

LimitX


1 Answers

It seems that you are trying to access from one domain https://foo.bar into another domain at https://myrest.api and that is the reason for that error.

You have 2 options:

1) Merge this 2 apps into one single domain on Heruko, React and the Api apps will be under https://foo.bar domain for example and that will work for you.

2) Allow the client app domain at https://foo.bar to access into your api domain at https://myrest.api by adding "Access-Control-Allow-Origin" header into the api app:

app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   next();
});
like image 186
Sagi Tsofan Avatar answered Sep 28 '22 06:09

Sagi Tsofan