我正在开发与第三方API集成的ReactJS应用程序。我可以用Postman成功执行相同的请求,但是在浏览器中从React应用程序执行时,它们被阻止了。当我引用自己的后端时,我知道CORS以及如何解决该问题,但是在这种情况下,我显然不能。我尝试使用旨在执行类似操作的多个JS模块进行请求,但每个模块都有相同的错误。
Access to fetch at 'http://api.example.com/resource/request?param=value' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
import React, {Component} from 'react';
import fetch from 'fetch';
import request from 'request';
class App extends Component {
render() {
return (
<div className="App">
<button onClick={this.sendWithXmlHttpRequest}>send XMLHttpRequest
</button>
<button onClick={this.sendWithFetch}>send Fetch</button>
<button onClick={this.sendWithRequest}>send Eequest</button>
</div>
);
};
sendWithXmlHttpRequest = () => {
let req = new XMLHttpRequest();
req.open('get', url, true);
req.send();
};
sendWithFetch = () => {
fetch.fetchUrl(url, (error, meta, body) => {
console.log(error, meta, body);
});
};
sendWithRequest = () => {
request.get(url);
};
}
const url = 'http://api.example.com/resource/request?param=value';
export default App;
答案 0 :(得分:1)
假设您使用Node作为后端。从服务器端将Access-Control-Allow-Origin标头发送为*,以便客户端了解服务器策略。您还可以添加cors npm软件包来为您完成这项工作。以下是我如何在快递方面解决此问题的代码:
app.use(function(req, res, next) {
res.header(“Access-Control-Allow-Origin”, “*”);
res.header(“Access-Control-Allow-Methods”, “GET,PUT,POST,DELETE”);
res.header(
“Access-Control-Allow-Headers”,
“Origin, X-Requested-With, Content-Type, Accept”
);
next();
});
app.options(“*”, cors());
此外,您可以在浏览器上安装一些CORS扩展并启用请求。 一种这样的扩展 https://chrome.google.com/webstore/detail/moesif-orign-cors-changer/digfbfaphojjndkpccljibejjbppifbc
答案 1 :(得分:1)
这可以解决问题,但是我不认为您愿意将其包含在Production Ready应用程序中。
sendWithXmlHttpRequest = () => {
// Added a Proxied server which works as a middle-man to fetch the data for you.
const urlWithProxy = `https://cors-anywhere.herokuapp.com/${url}`
let req = new XMLHttpRequest();
req.open('get', url, true);
req.send();
};
这是from.。
一种更可取的方法是让一个server.js
服务于捆绑的应用程序,并且-可能很少-需要一些请求策略,但是,我希望没有配置就足够了,因为请求是将通过Node not React进行代理。