Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $http.delete request with body

So I looked at this post: is an entity body allowed for an http delete request

Which seems to indicate that while it is 'ok' to do on some conceptual level, in practice it may not be doable because browsers just ignore it.

I have some express.js authentication middleware I need to get through, and I don't want to attach my user details to url params. All my other requests that need to authenticate attach these details to the body of the request.

Is there some way to force this? I saw some other posts where some people seemed to have success in passing a body with their delete request.

I am running a node/sails back-end. It always logs the body as undefined for a delete request. Is there any way to modify

like image 599
tpie Avatar asked Apr 22 '15 07:04

tpie


2 Answers

The sails API pulls the id of the object to delete from the params, so we have to append the id to the url.

But if I want to pass some authentication details in a body for server-side verification before processing the delete request, I can't just stick them in an object as the second parameter of the delete request, like you can with $http.post.

Angular's post method automatically assigns whatever we insert as a second parameter to the body of the request, but the delete method does not.

Angular's $http.delete method does allow us to supply a config object as the second parameter, through which we can get access to the 'data' property. This is the same way post does it through it's second parameter.

So if we need to attach a body to a delete request we can use the following:

$http.delete('/api/' + objectToDelete.id, {data: {id: currentUser().id, level: currentUser().level}});

This will pass the object to delete's id in the url parameter, and my user credentials in the body as an object.

like image 156
tpie Avatar answered Sep 27 '22 20:09

tpie


Honestly, everytime a trouble sounds like a "restriction of as REST", a rethink of the strategy and the philosophy might be a good idea.

I have some authentication middleware I need to get through

I don't want to attach my user details to url params

I'm not directly answering the question, but you should know that among the commons

  • URL parameters (or query, but URL anyway)
  • Body

there is a third option for "passing values to the server" :

  • request Headers

I'd just suggest to consider that third option to provide your credentials: request header.

Edit : following appendix would just apply to any "external" middleware, like a proxy server or whatever, not a true express middleware inside sails.js

In addition, that would be a good idea that your middleware stripped those headers before redirecting to the real action.

like image 28
Cyril CHAPON Avatar answered Sep 27 '22 19:09

Cyril CHAPON