"Access-Control-Allow-Origin" issue when calling an API from React (Isomorphic app)

I am having a problem with my isomorphic JavaScript application using React and Express.

I am trying to make an HTTP request using axios.get when my component mounts

componentDidMount() { const url = 'http://ufc-data-api.ufc.com/api/v3/iphone/fighters/title_holders'; axios.get(url).then( res => { //use res to update current state }) } 

I get 200 res status from the API, but I don't get any response data and get an error message in my console

 XMLHttpRequest cannot load http://ufc-data-api.ufc.com/api/v3/iphone/fighters/title_holders. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. 

However, if I make a request in my server.js

 const url = 'http://ufc-data-api.ufc.com/api/v3/iphone/fighters/title_holders'; axios.get(url).then(res => { //console.log(res); }); 

It works fine, and I get response data when the server starts. Is this a problem with the actual API, or am I doing something wrong? If this is a CORS problem, I assume the request in server.js will not work either? Thanks!

+8
javascript reactjs axios isomorphic-javascript
source share
4 answers

CORS is a browser . Servers must choose in CORS so that browsers bypass a policy of the same origin. Your server will not have the same restriction and will be able to send requests to any server with an open API. https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Create an endpoint on your server with CORS enabled, which can act as a proxy for your web application.

+6
source share

Use the Google Chrome extension called Allow-Control-Allow-Origin: * . It changes the CORS headers on the fly in your application.

+6
source share

I think the answer to your question is here

For Chrome to send Access-Control-Allow-Origin to the header, just add the alias of your local host to the / etc / hosts file in some other domain, for example:

127.0.0.1 localhost yourdomain.com

+1
source share

Since the server does not have a CORS header, you are not allowed to receive a response.

This is the header from the API that I grabbed from the Chrome browser:

 Age:28 Cache-Control:max-age=3600, public Connection:keep-alive Date:Fri, 06 Jan 2017 02:05:33 GMT ETag:"18303ae5d3714f8f1fbcb2c8e6499190" Server:Cowboy Status:200 OK Via:1.1 vegur, 1.1 e01a35c1b8f382e5c0a399f1741255fd.cloudfront.net (CloudFront) X-Amz-Cf-Id:GH6w6y_P5ht7AqAD3SnlK39EJ0PpnignqSI3o5Fsbi9PKHEFNMA0yw== X-Cache:Hit from cloudfront X-Content-Type-Options:nosniff X-Frame-Options:SAMEORIGIN X-Request-Id:b971e55f-b43d-43ce-8d4f-aa9d39830629 X-Runtime:0.014042 X-Ua-Compatible:chrome=1 X-Xss-Protection:1; mode=block 

There is no CORS header in the response headers.

0
source share

All Articles