如何启用DELETE请求?

时间:2016-10-05 14:03:18

标签: express cors

由于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请求一样?

3 个答案:

答案 0 :(得分:17)

我在没有添加新包的情况下解决了它,只是添加了这一行

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();
});

答案 1 :(得分:4)

您的某个标题未正确设置,因此不是

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

把它作为

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

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

答案 2 :(得分:0)

只需使用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')());

但是我仍然不确定魔法包的内容是如何做的。

相关问题