从React(Isomorphic应用程序)进行API调用时出现“Access-Control-Allow-Origin”问题 [英] 'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)
问题描述
我使用React和Express遇到了我的同构JavaScript应用程序的问题。
I'm running into an issue with my isomorphic JavaScript app using React and Express.
我正在尝试使用axios.get在我的组件安装时发出HTTP请求
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
})
}
我从API获得状态200 res,但我没有收到任何响应数据并在我的控制台中出错
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.
但是,如果我在我的server.js中提出请求
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);
});
它工作正常,我在服务器启动时获得响应数据。这是实际API的问题还是我做错了什么?如果这是一个CORS问题,我猜测server.js中的请求也不起作用?谢谢!
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!
推荐答案
CORS是浏览器功能。服务器需要选择加入CORS以允许浏览器绕过同源策略。您的服务器不会受到相同的限制,并且能够使用公共API向任何服务器发出请求。 https://developer.mozilla.org/en-US/docs/Web / HTTP / Access_control_CORS
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
在服务器上创建一个端点,启用CORS,可以充当您的Web应用程序的代理。
Create an endpoint on your server with CORS enabled that can act as a proxy for your web app.
这篇关于从React(Isomorphic应用程序)进行API调用时出现“Access-Control-Allow-Origin”问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!