无法在服务器端NodeJS上启用CORS



我无法在服务器端启用CORS。我的前端和后端服务器有不同的端口。以下是服务器端的实现方式:

http
.createServer(function (req, res) {
// .. Here you can create your data response in a JSON format
// const { headers, method, url } = req;
// let body = [];
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
res.setHeader('Access-Control-Allow-Headers', '*');
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
// const responseBody = { headers, method, url, body: JSON.stringify(data) };
response.write('{asd: 123}'); // Write out the default response
res.end(); //end the response
})
.listen(port);

我从前端调用fetch函数,如下所示:

fetch('http://localhost:3035', {
method: 'POST',
mode: 'same-origin', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'include', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify(line), // body data type must match "Content-Type" header
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.log(error));

但仍有错误:

Security Error: Content at http://localhost:3030/ may not load data from http://localhost:3035/.

TypeError: "NetworkError when attempting to fetch resource."

通过设置mode: 'same-origin'而不是默认的mode: 'cors',显式地禁止客户端上的CORS。

引用文档:

same-origin——如果使用此模式设置向另一个原点发出请求,则结果只是一个错误。您可以使用它来确保始终向您的原籍国提出请求。

由于http://localhost:3035/http://localhost:3030/的另一个原点,因此结果与设计完全一样;只是一个错误";。

将其设置为mode: 'cors'或完全删除mode,因为无论如何cors都是默认值。


附带说明,Access-Control-Request-Method是飞行前请求中的请求标头,而不是响应标头。你应该删除它。


如评论中所述:对于有资格的工作请求,您不能使用允许的*来源。但是,如果您不想在此时对期望的原点进行硬编码,则可以通过始终使用res.setHeader('Access-Control-Allow-Origin', req.headers.origin)返回当前请求的原点来避免此问题。

最新更新