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

标签 javascript node.js express error-handling cors

我在后端有一个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/

相关文章:

javascript - 带有 node.js 0.10 的 UDP 套接字上的 ENOTFOUND 错误

angularjs - 在 AngularJS 中本地保存 session 有多安全?

node.js - 从 Express 服务器响应中获取/读取 res.status() 值

file - Express 和 Multer 上传问题 - req.files 始终为空

javascript - jquery 重新加载后未解析 dojo 组件

javascript - 如何根据条件延迟循环?

php - Joomla 2.5模态弹出组件表单

firefox - Socket.io 无法向 Chrome 和 Firefox 上的 Node 服务器发送消息

javascript - 图像未在带有参数的路线上加载,但在没有参数的路线上有效

javascript - 如何在 multer 中上传带有可选数据的图像?