I have a form here with the delete method being used:
<form action="/article/<%= articles[i]._id %>" method="DELETE"><button 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.
CodePudding user response:
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>
CodePudding user response:
<form action="/article/<%= articles[i]._id %>" method="POST">
<input type="hidden" name="_method" value="DELETE">
<button type="submit">Delete</button></form>
**Try This Way **