gpt4 book ai didi

javascript - Express.js CORS配置,PUT不起作用?

转载 作者:行者123 更新时间:2023-12-03 09:02:48 24 4
gpt4 key购买 nike

我在后端有一个React应用程序和Nodejs(Express)。部署到主机服务器后,我执行的用于更新某些文档的功能将无法正常工作。它给出了CORS错误:

enter image description here

我有以下代码行可以处理server.js中的CORS策略:

app.use((req, res, next) => {
res.set({"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Methods" : "HEAD, OPTIONS, GET, POST, PUT, PATCH, DELETE",
"Access-Control-Allow-Headers" : "Content-Type, Authorization, X-Requested-With"})
next();
});

可以使用GET和POST方法,但不适用于PUT(不知道是否没有尝试过Delete方法)

我在这个问题上花了很多时间;尝试了这个: https://stackoverflow.com/a/42463858/11896129

在网上寻找了一堆解决方案,尝试从IIS web.config文件中对其进行配置,但没有任何解决方案可以解决我的问题。我想念哪一部分?

最佳答案

MDN:所述

Additionally, for HTTP request methods that can cause side-effects on server's data (in particular, for HTTP methods other than GET, or for POST usage with certain MIME types), the specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request method, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method.



因此,您必须回答飞行前的要求:
  app.options("*", (req, res) => {
res.status(200).send("Preflight request allowed");
});

阅读有关预检请求 here的更多信息。

关于javascript - Express.js CORS配置,PUT不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60631168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com