使用 express 和 body-parser 解析 DELETE 请求时 body 为空

body is empty when parsing DELETE request with express and body-parser

我正在使用 expressjs 和 body-parser 中间件。

我是这样启动的:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

我从客户端发送了一个 DELETE 请求,当我尝试从服务器端获取它时,我得到一个空对象:

app.delete('/', function(req, res) {
    console.log(util.inspect(req.body)); //outputs {}
    //some more code
});

然而,当我用 POST 发送它时,我得到了我需要的东西:

app.post('/delete', function(req, res) {
    console.log(util.inspect(req.body)); //outputs { mid: 'ffw1aNh2' }
    //some more code
});

值得注意的是,我没有在客户端进行任何更改 (angularjs),但是方法和 url 以及 firefox 网络调试器显示了在这两种情况下发送的数据.

这里缺少什么?为什么我在 delete 方法上得到一个空的正文对象?

$http 服务源代码,使用 $http 的 DELETE 请求不允许在请求正文中发送数据。

DELETE 请求的规范在是否允许请求正文方面有些模糊,但 Angular 不支持它。

The only methods that allow for request bodies are POST, PUT, and PATCH. So the problem is not anywhere in your code, its in Angular's $http service.

使用这个

$httpProvider.defaults.headers.delete = { "Content-Type": "application/json;charset=utf-8" };

然后

$http.delete(url, { data: data })