【发布时间】:2019-06-12 08:54:22
【问题描述】:
我正在尝试调用安装在本地服务器中的流行服务器(如 OwnCloud、Openfire 和 Ejabberd)的 API。我正在创建一个 ReactJS 网站。最初,我使用 fetch() 方法来访问 API。但结果是我收到了 CORS 错误。
Access to fetch at 'http://x.x.x.x:8088/api/contacts/3000@x.x.x.x' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field cache-control is not allowed by Access-Control-Allow-Headers in preflight response.
我使用 Postman 检查了相同的 API 并成功获得了响应。然后我用命令行下面的节点代码测试了一下,在命令行中得到了API响应。
var http = require("http");
var options = {
"method": "GET",
"hostname": "x.x.x.x",
"port": "8088",
"path": "/api/contacts/3000@x.x.x.x",
"headers": {
"cache-control": "no-cache",
"postman-token": "e5a6f2bb-abc9-8ce7-f237-342ab53ab9d6"
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.end();
我在我的 ReactJS 代码中实现了相同的节点代码并再次遇到相同的 CORS 错误。
我已将以下标头添加到 fetch() 方法的标头并得到相同的 CORS 错误。
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
'Access-Control-Allow-Headers': 'origin, content-type, accept, authorization',
我在 fetch() 方法中添加了 mode: "cors"。但还是同样的错误。
您能否提供一个解决方案来避免这个 *CORS* 问题?
【问题讨论】:
-
也许这个解决方案适合你。 stackoverflow.com/questions/25727306/…
标签: node.js reactjs npm cors cross-domain