Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...