[英]Unable to fetch JSON from Express server using Fetch api
在端口 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。
我已经阅读了多个帖子来解决这个问题,但我似乎仍然无法解决它。
我应该如何获取以避免此错误?
您正在从不同的端口 (8081) 获取数据,这就是您收到 CORS 错误消息的原因。 更改访问控制策略如下:
res.header("Access-Control-Allow-Origin", "http://localhost:*");
这个链接可以派上用场。
您可以使用cors
来摆脱这种情况;
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.