Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.
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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading