我在使用 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 中的请求也不起作用?谢谢!
原文由 Scott Davidson 发布,翻译遵循 CC BY-SA 4.0 许可协议
CORS 是一种 浏览器 功能。服务器需要选择加入 CORS 以允许浏览器绕过同源策略。您的服务器将没有相同的限制,并且能够使用公共 API 向任何服务器发出请求。 https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
在您的服务器上创建一个启用了 CORS 的端点,该端点可以充当您的 Web 应用程序的代理。