'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)


I'm running into an issue with my isomorphic JavaScript app using React and Express.

I am trying to make an HTTP request with 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 am getting a status 200 res from the API, but I am not getting any response data and getting an error 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 the request in my server.js

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

It works fine and I get response data when the server starts. Is this an issue with the actual API or am I doing something wrong? If this was a CORS issue I'm guessing the request in server.js wouldn't work either? Thanks!

Show source
| javascript   | reactjs   | node.js   | isomorphic-javascript   | axios   2017-01-06 02:01 3 Answers

Answers ( 3 )

  1. 2017-01-06 03:01

    Because the server don't have CORS header, so you are not allowed to get the response.

    This is header from API that I captured from Chrome brower:

    Cache-Control:max-age=3600, public
    Date:Fri, 06 Jan 2017 02:05:33 GMT
    Status:200 OK
    Via:1.1 vegur, 1.1 e01a35c1b8f382e5c0a399f1741255fd.cloudfront.net (CloudFront)
    X-Cache:Hit from cloudfront
    X-Xss-Protection:1; mode=block

    No CORS header in response headers.

  2. 2017-01-06 03:01

    CORS is a browser feature. Servers need to opt into CORS to allow browsers to bypass same-origin policy. Your server would not have that same restriction and be able to make requests to any server with a public API. https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

    Create an endpoint on your server with CORS enabled that can act as a proxy for your web app.

  3. 2017-01-06 03:01

    I think the answer for your question is here

    To have Chrome send Access-Control-Allow-Origin in the header, just alias your localhost in your /etc/hosts file to some other domain, like: localhost yourdomain.com

◀ Go back