Form DELETE method is redirecting to the GET method instead in EXPRESS JS

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.

>Solution :

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.

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

// override with POST having ?_method=DELETE
<!-- HTML Form using DELETE -->
<form method="POST" action="/resource?_method=DELETE">
  <button type="submit">Delete</button>

Leave a Reply