【问题标题】:How to enable DELETE request?如何启用 DELETE 请求?
【发布时间】:2017-02-14 00:36:09
【问题描述】:

由于 CORS,我无法允许来自我的 API 服务器的 DELETE 请求。

server.js

// enable CORS
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET", "PUT", "POST", "DELETE", "OPTIONS");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    next();
});

我收到一个控制台错误提示:

XMLHttpRequest cannot load http://localhost:8080/api/users/57f5036645c04700128d4ee0. Method DELETE is not allowed by Access-Control-Allow-Methods in preflight response

如何启用DELETE 请求,就像GETPUTPOST 请求一样?

【问题讨论】:

  • @UmakantMane 我更新了我的前端请求:$.ajax({ async: true, crossDomain: true, url: '...', method: 'DELETE', headers: { 'content-type': 'application/x-www-form-urlencoded', 'Authorization': '...' } });,但这并没有帮助
  • @UmakantMane 发表评论而不是建议

标签: express cors


【解决方案1】:

我没有添加新包就解决了,只是添加了这一行

res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");

请注意,我允许的方法在一个字符串中用逗号分隔。 完整的函数如下所示:

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  next();
});

【讨论】:

    【解决方案2】:

    您的一个标题设置不正确,所以不是

    res.header("Access-Control-Allow-Methods", "GET", "PUT", "POST", "DELETE", "OPTIONS");
    

    把它当作

    res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
    

    但你是对的,使用 npm 包更简单。

    【讨论】:

      【解决方案3】:

      通过简单地使用 npm 的 cors 包并启用所有 cors 请求来解决它,只需替换...

      // enable CORS
      app.use(function (req, res, next) {
          res.header("Access-Control-Allow-Origin", "*");
          res.header("Access-Control-Allow-Methods", "GET", "PUT", "POST", "DELETE", "OPTIONS");
          res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
          next();
      });
      

      与...

      app.use(require('cors')());
      

      但我仍然不确定 Magic cors 包在引擎盖下做了什么来使其工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多