1

I have a form here with the delete method being used:

<form action="/article/<%= articles[i]._id %>" method="DELETE"><button class="btn btn-danger" type="submit">Delete</button></form>

Then my routes for the article ID's look like this:

const articleById = require('../controllers/article/articleById')
router.get('/:id', articleById)

const deleteArticleById = require('../controllers/article/deleteArticleById')
router.delete('/:id', authLoggedIn, deleteArticleById)

The form should be using the router.delete with its controller but instead it is using the router.get and using that controller instead. I verified this by using console.log in each controller and when I submit that form it will send me to router.get instead. I'm not sure how to get the form to use the router.delete.

  • 1
    Does this answer your question? [Using PUT method in HTML form](https://stackoverflow.com/questions/8054165/using-put-method-in-html-form) – Montgomery Watts Jun 14 '22 at 04:31
  • From the duplicate, see [this answer](https://stackoverflow.com/a/65630961/283366) for the server side and [this answer](https://stackoverflow.com/a/8054241/283366) for the client side – Phil Jun 14 '22 at 04:34

2 Answers2

3

HTML Form doesn't support PUT, PATCH, DELETE method. Form only support GET and POST method. Thats why method="DELETE" is not working and instead it calls GET.

But you can override this behaviour using method-override package. http://expressjs.com/en/resources/middleware/method-override.html

var express = require('express')
var methodOverride = require('method-override')
var app = express()

// override with POST having ?_method=DELETE
app.use(methodOverride('_method'))
<!-- HTML Form using DELETE -->
<form method="POST" action="/resource?_method=DELETE">
  <button type="submit">Delete</button>
</form>
Phil
  • 157,677
  • 23
  • 242
  • 245
Abhishek
  • 726
  • 3
  • 10
  • Why `/resource`? Why not use the actual URL in OP's question? – Phil Jun 14 '22 at 04:38
  • Awesome, that worked perfectly. Always thought that DELETE was a standard html thing that could be used in forms. Maybe I just got that idea from CRUD or something? – DeveloperLewis Jun 14 '22 at 04:40
  • @DeveloperLewis modern forms still not supporting other methods. You can use fetch also to perform delete here. `fetch('/resource', {method: "DELETE"}).then(res => res.json()).then(data => console.log(data))` – Abhishek Jun 14 '22 at 04:49
  • @Phil I was trying make the solution more generic. I am a new here in terms of answering and I don't know much about rules. – Abhishek Jun 14 '22 at 04:52
0
<form action="/article/<%= articles[i]._id %>" method="POST">
<input type="hidden" name="_method" value="DELETE">
<button class="btn btn-danger" type="submit">Delete</button></form>

**Try This Way **

Amir Ojha
  • 11
  • 1
  • Won't OP also need the [method override middleware](http://expressjs.com/en/resources/middleware/method-override.html)? – Phil Jun 14 '22 at 04:31