从React(Isomorphic应用程序)进行API调用时出现“Access-Control-Allow-Origin”问题

问题描述 投票:16回答:6

我使用React和Express遇到了同构JavaScript应用程序的问题。

我正在尝试使用axios.get在我的组件安装时发出HTTP请求

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,但我没有得到任何响应数据并在我的控制台中收到错误

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中发出请求

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中的请求也不起作用?谢谢!

javascript node.js reactjs isomorphic-javascript axios
6个回答
15
投票

CORS是一种浏览器功能。服务器需要选择加入CORS以允许浏览器绕过同源策略。您的服务器不会受到相同的限制,并且能够使用公共API向任何服务器发出请求。 https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

在服务器上创建一个端点,启用CORS,可以充当您的Web应用程序的代理。


16
投票

使用名为Allow-Control-Allow-Origin: *的Google Chrome扩展程序。它会在您的应用程序中动态修改CORS标头。


2
投票

我认为你的问题的答案是here

要让Chrome在标头中发送Access-Control-Allow-Origin,只需将/ etc / hosts文件中的localhost别名替换为其他域,例如:

127.0.0.1 localhost yourdomain.com


0
投票

因为服务器没有CORS头,所以不允许您获得响应。

这是我从Chrome浏览器中捕获的API标题:

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

响应头中没有CORS头。


0
投票

我不知道这是否会有所帮助,但是在远程调试react-native应用程序时遇到了同样的错误。我在192.168.x.x:8081上运行调试器。我读了一下这个Cross-Origin Resource Sharing (CORS),以了解CORS是什么。 (我是初学者)并将我的URL从IP:8081更改为localhost:8081,我的问题已解决。


0
投票

我有同样的问题。其他答案是正确的,但还有另一种解决方案。您可以设置响应标头以允许跨源访问。根据this post,您必须在任何app.get调用之前添加以下代码:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
  });

这对我有用:)

© www.soinside.com 2019 - 2024. All rights reserved.