[英]Fetch problem with node.js express server
我在使用 fetch 和 node.js 时遇到了一些问题。 在我的前端,当我单击一个按钮时,我想发送一个发布请求,以便从我的后端接收一个数组作为答案。 我在我的后端使用 node.js 和 express,在我的前端我使用 fetch 函数。
发生的错误如下:
CORS 策略已阻止从源“真实本地主机地址”获取“http://localhost:8080/api”的访问权限:请求的资源上不存在“Access-Control-Allow-Origin”标头。 如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
代码在这里
const getArray = async() => {
const data = await fetch ("http://localhost:8080/api");
const dataJson = await data.json();
console.log(dataJson)
}
getArray();
在我的服务器中,我有
app.post("/api", (req,res) => {
res.sendFile(JSON.stringify(arr));
});
您需要添加请求选项。 请参阅MDN文档以获取更多信息。
正如@Kudah 所说,您应该阅读文档。
Fetch(和 XMLHttpRequest)遵循同源策略。 这意味着浏览器会限制来自脚本的跨域 HTTP 请求。 当一个域(例如http://example2.com/ )从另一个域(例如http://example1.com/ )请求资源时,就会发生跨域请求。
解决这个问题的最简单方法,(如果你不想深入研究这个)
const whiteList = [ "https://myRealBackendUrl-1", "https://myRealBackendUrl-2" ];
// you can also pass a string here instead here instead of array
const corsOptions = {
credentials: true,
origin: process.env.NODE_ENV !== production ? "http://localhost:4000" : whiteList
// if you are in a dev environment, you probably want something like localhost
// http://localhost:4000 is just a demo backend. replace it with your own.
// if you are in a production environment, for example heroku then your backend
// url will be something like http://example.herokuapp.com
// in that case `const whiteList = [ "http://example.herokuapp.com" ];`
};
app.use(cors(corsOptions));
上面的代码对于正常的用例应该足够了。
还有回调函数,如果你想运行你自己的一些函数。 如果您不打算使用任何动态检查,请不要阅读它
var corsOptionsDelegate = async (req, callback) => {
var corsOptions = { origin: false };
try {
// you can do some dynamic check here
// For example: check database for some conditions then allow access
if( myDatabaseSays == true ) corsOptions.origin = true;
else corsOptions.origin = false;
} catch (err) {
console.log(err);
// corsOptions.origin = false;
}
callback(null, corsOptions) // chain it
}
无论如何,请正确阅读文档以获取更多信息 [1]: https ://expressjs.com/en/resources/middleware/cors.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.