Send Angular $http.delete with body

不羁岁月 提交于 2021-01-27 14:30:35

问题


In my Angular app, I need to send an $http.delete request this route /projects/:id/activityTypes (note it does not end with an activity type id) passing a body with the following format:

[{"id": 2}]

This is to allow batch delete operations by sending multiple objects within the array.

Testing the route above with Rest Web Service Client I get a 200, OK status so the route is already implemented and working fine, I just need to implement it in my Angular app.

Now, I've checked this previous post which has a very similar question and learned that angular's $http.delete does not send a body in the request by default, but that:

[it] does allow us to supply a config object as the second parameter, through which we can get access to the 'data' property.

So I tried what was suggested and sent a config object in my request:

return $http.delete('projects/' + projectID + '/activityTypes', {data: [{id: 2}]})

However, it does not work. It seems that although I am sending this config object, I am still not sending a body.

How can I actually pass a body to my $http.delete route?

EDIT: Here is what the server is logging when I send the $http.delete request above:

The data appears to have been sent, but I get this console error which I don't get when using the Rest Client:

Object {data: "Json not valid to remove activity type from Project", status: 400, config: Object, statusText: "Bad Request"}

回答1:


try this:

$http({
            method: 'DELETE',
            url: 'projects/' + projectID + '/activityTypes',
            data: [{id: 2}]},
            headers: {
                'Content-type': 'application/json;charset=utf-8'
            });



回答2:


@Renato's approach will work, but so would the $http.delete(...) approach, with a little tweaking. By including the data element in the request options, you do pass along data to the server, and you can confirm this in your Developer's Console. However, without the appropriate Content-Type, your server may likely ignore it.

The following should work:

return $http.delete('projects/' + projectID + '/activityTypes', {data: [{id: 2}], headers: {'Content-Type': 'application/json;charset=utf-8'}})

Credit goes to @Harshit Anand for his on another SO post.



来源:https://stackoverflow.com/questions/33235074/send-angular-http-delete-with-body

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