Reactjs 如何防止CORS策略阻止从本地主机到第三方API的请求?

Reactjs 如何防止CORS策略阻止从本地主机到第三方API的请求?,reactjs,cors,xmlhttprequest,Reactjs,Cors,Xmlhttprequest,我正在开发与第三方API集成的ReactJS应用程序。我可以使用Postman成功地执行相同的请求,但当从浏览器中的React应用程序执行时,这些请求被阻止。当我引用自己的后端时,我知道CORS以及如何解决问题,但在这种情况下,我显然不能。我试着用几个JS模块来处理请求,但每个模块都有相同的错误 Access to fetch at 'http://api.example.com/resource/request?param=value' from origin 'http://localhos

我正在开发与第三方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}来自'React';
从“fetch”导入fetch;
从“请求”导入请求;
类应用程序扩展组件{
render(){
返回(
发送XMLHttpRequest
送取
发送电子邮件
);
};
sendWithXmlHttpRequest=()=>{
让req=newXMLHttpRequest();
请求打开('get',url,true);
请求发送();
};
sendWithFetch=()=>{
fetch.fetchUrl(url,(错误、元、正文)=>{
日志(错误、元、正文);
});
};
sendWithRequest=()=>{
获取(url);
};
}
常量url=http://api.example.com/resource/request?param=value';
导出默认应用程序;

假设您将节点用于后端。从服务器端将Access Control Allow Origin标头作为*发送,以便客户端了解服务器策略。您也可以添加cors npm包来完成这项工作。下面是我如何在express端解决此问题的代码:

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扩展并启用请求。 一个这样的扩展

这解决了问题,但我认为您不愿意将其包含在生产就绪的应用程序中

  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();
  };
这是


更可取的方法是使用一个为捆绑应用提供服务的
server.js
,它可能(可能性很小)需要一些请求策略,但是,按照我的预期,不进行配置就足够了,因为请求将通过节点代理而不会发生反应。

检查此项-谢谢,但不幸的是,我无法控制后端。我只能嘲笑它,但这不是我想要达到的。谢谢。这对于开发和本地测试非常有用。您是否考虑过为生产目的制作一个简单的服务器?
  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();
  };