How do you send a request using the HTTP DELETE request?

I would like to create a link in a view in a Rails application that does this ...

DELETE /sessions 

How I would do it.

Added complication:

The session resource does not have a model because it is a user login session. CREATE means that the user logs in, DESTROY means that they DESTROY out.

This is why there is no identification parameter in the URI.

I am trying to implement a logout link in the user interface.

+5
source share
4 answers

That's right, browsers do not actually support sending removal requests. The accepted convention of many web frameworks is to send the _method parameter to "DELETE" and use the POST request.

Here is an example in Rails:

 <%= link_to 'log out', session_path, :method => :delete %> 

You might want to check out Restful Authentication .

+18
source

I don’t know about Rails specifically, but I often create web pages that send DELETE (and PUT) requests using Javascript. I just use XmlHttpRequest objects to send the request.

For example, if you use jQuery:

there is a link that looks like this:

 <a class="delete" href="/path/to/my/resource">delete</a> 

And run this javascript:

 $(function(){ $('a.delete').click(function(){ $.ajax( { url: this.getAttribute('href'), type: 'DELETE', async: false, complete: function(response, status) { if (status == 'success') alert('success!') else alert('Error: the service responded with: ' + response.status + '\n' + response.responseText) } } ) return false }) }) 

I wrote this example mainly from memory, but I'm sure it will work.

+4
source

Correct me if I am wrong, but I believe that you can send POST and GET requests only in the browser (in HTML format).

+1
source

The built-in Rails method for links will generate something like this:

 <a href="/sessions?method=delete" rel="nofollow">Logout</a> 

If you do not want to use the built-in Rails method (that is, you do not want rel="nofollow" , which prevents tracking of search engines from the link), you can also manually write the link and add the data-method attribute, for example:

 <a href="/sessions" data-method="delete">Logout</a> 

Browsers can only send GET / POST requests, so it will send a regular GET request to your Rails server. Rails interprets and directs this as a DESTROY / DELETE request and invokes the corresponding action.

+1
source

Source: https://habr.com/ru/post/900135/


All Articles