Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'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 => {     //console.log(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!

like image 492
Scott Davidson Avatar asked Jan 06 '17 01:01

Scott Davidson


People also ask

How do you Access-Control allow origin in react?

Inside the request middleware callback, I first set the Access-Control-Allow-Origin header to an asterisk. The asterisk indicates that this resource can be requested by any client. Let's also change the endpoint in our React app. const response = await fetch('http://localhost:8080/cors', { mode: 'cors' });

How do you overcome the CORS issue in Reactjs?

Simple proxy server that runs on localhost:3001: use(cors(corsOptions)); const proxyMiddleware = createProxyMiddleware("/", { target: "https://....api origin.....com", changeOrigin: true, }); app. use(proxyMiddleware); app. listen(3001, () => { console. log("proxy is listening on port 3001"); });

How do I fix CORS header Access-Control allow Origin missing?

If the server is under your control, add the origin of the requesting site to the set of domains permitted access by adding it to the Access-Control-Allow-Origin header's value. You can also configure a site to allow any site to access it by using the * wildcard. You should only use this for public APIs.


1 Answers

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.

like image 186
azium Avatar answered Oct 02 '22 17:10

azium