Search code examples
javascriptnode.jsformspostput

Using PUT to delete in Node.js


In node.js, I can use

app.route('/').get(getObjectList).post(postAddObject).put(putDeleteObject);

but I don't know how to trigger ...put(putDeleteObject) in html.

Is it true that we are limited to post and get in html? When can I then use put? Is it only for REST requests through, for instance, jQuery?

How do you normally delete objects? I think it is more safe to go through a post request rather than a get request, but it would be great to chain it like I did in the code example, however, it is probably not possible if the html cannot distinguish between post and put. I have seen some examples where they use

<form method="post">
  <input type='hidden' name='_method' value='put'>
  <button type='submit'>Delete</button>
</form>

but it doesn't work for me.

Edit

I meant to use DELETE and not PUT, but the problem stay the same. I don't know how to change my html to support the DELETE request.


Solution

  • You didn't include it in the question but it looks like you're using Express. In that case you can use:

    var methodOverride = require('method-override')
    app.use(methodOverride('_method'))
    

    And then you'll be able to use HTML forms like this one:

    <form method="POST" action="/your/resource?_method=DELETE">
      <button type="submit">Delete</button>
    </form>
    

    And this in your route handlers:

    app.route('/')
      .get(getObjectList)
      .post(postAddObject)
      .put(putObject)
      .delete(deleteObject);
    

    If you want to use:

    <form method="POST">
      <input type="hidden" name="_method" value="delete">
      <button type="submit">Delete</button>
    </form>
    

    then it's a little bit more complicated but still possible - for more info see: