【发布时间】:2020-05-31 05:22:10
【问题描述】:
在端口 8080 上运行的 Express 服务器中,我有;
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8081");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
来自 8081 端口的请求
fetch('http://localhost:8080/...')
.then((response) => response.json())
.then((json) => {
let jsonStr = JSON.stringify(json);
console.log(jsonStr)
})
.catch((error) => console.log(error))
我得到的错误:
Access to fetch at 'http://localhost:8080/...' from origin 'http://localhost:8081' 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.
如果我只是在浏览器上手动输入 express url,我会看到我正在尝试获取的 JSON。
我已经阅读了多篇文章来解决这个问题,但我似乎仍然无法解决它。
我应该如何获取以避免此错误?
【问题讨论】:
标签: javascript express cors es6-promise fetch-api