lobengula3rd lobengula3rd - 6 months ago 90
Node.js Question

angular $resource delete won't send body to express.js server

hye,

i am building an app with angular.js and node.js (Express.js) on the server side.

for some reason i am having a problem handling a delete request. no body is getting to the server side.

this is my angular.js resource code:

$scope.deleteProject = function(projectName){
var postData = {username: 'name', projectName: projectName};
Project.deleteProject.delete({}, postData,
function(res){
alert('Project Deleted');
},
function(err){
alert(err.data);
});
}


on the server side i have this:

var deleteProject = function(req, res){
console.log(req.body);
console.log(req.params);
if (req.body.projectName){
//do something
return res.send(200);
}
else
return res.send(400, 'no project name was specified');
}


now for some reason there is no body at all!! it is empty.
i have defined the route as app.delete.

if i change the route in node.js to post and in angular.js to save it works fine.

what am i missing here (banging my head).

thanks.

Answer

As per this stack overflow question and 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.

My suggestion would be to use the generic $http(...) function and pass in the proper method:

$http({
    method: 'DELETE',
    url: '/some/url',
    data: {...},
    headers: {'Content-Type': 'application/json;charset=utf-8'}
})
Comments