How to use other HTTP methods in HTML forms?

Asked

Viewed 523 times

2

I’m using Express.JS to make a CRUD in Nodejs.

I was trying to make use of the new HTTP methods, such as put , but when I put it in the attribute method of the apparently not certain form.

The code of the form:

[...]

<form action="/post/content" method="put">

[...]

How do I make it work?

A part of the back-end code:

app.put('/post/content', (req, res) => {
  console.log(req.body);
});

1 answer

2


The solution

The method PUT does not exist in HTML standards. The DELETE neither.

It is common to use this workaround:

<form method="post">
  <input type="hidden" name="_method" value="put" />
  ...
</form>

Or make a XMLHttpRequest with the PUT in client-side Javascript.

Why there are no PUT and DELTE methods in HTML forms?

In the HTML5 sketches it was considered to use the methods PUT and DELETE and were even implemented in the Firefox browser in its version beta.

Consider PUT and DELETE support as method of form was discussed in W3C and closed as "solved, but will not be corrected" for the following reason (translation and emphasis my):

PUT AS A method of form doesn’t make any sense. You wouldn’t want a PUT on payload of a form. DELETE only makes sense when there is no payload, then it makes no sense in forms either.

The day I write this, in 2018, HTML forms only support GET and POST.

  • Fine, but how do I treat it in the back end?

  • No need to change the back-end.

  • @lffg just use app.put like you’re already doing, so when you send via Xmlhttprequest with PUT it will run whatever’s in app.put, if you have an app.post won’t run, Express itself will already separate it for you. The app.get = ajax.open('GET', 'foo', true), app.post = ajax.open('POST', 'foo', true), app.put = ajax.open('PUT', 'foo', true) and app.delete = ajax.open('DELETE', 'foo', true)

  • Thank you very much,

Browser other questions tagged

You are not signed in. Login or sign up in order to post.