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

梦想的初衷 提交于 2019-12-20 01:06:28

问题


I'm using expressjs and the body-parser middleware.

This is how I initiate it:

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

From the client I'm sending a DELETE request and when I try to pick it up from the server side I get an empty object:

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

however when I send it with a POST I get what I need:

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

It is worth noting that I don't change anything on the client side (angularjs) but the method and the url and the firefox network debugger shows the data being sent in both situations.

What am missing here? Why am I getting an empty body object on a delete method?


回答1:


The $http service source code, a DELETE request using $http does not allow for data to be sent in the body of the request.

The spec for a DELETE request is somewhat vague on whether or not a request body should be allowed, but Angular does not support it.

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.

Use this

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

and then

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



来源:https://stackoverflow.com/questions/37796227/body-is-empty-when-parsing-delete-request-with-express-and-body-parser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!