:: krowemoh

Saturday | 28 DEC 2024
Posts Links Other About Now

previous
next

Using Put, Patch and Delete in Express

2022-11-13

To be able to handle http methods besides POST and GET, we will need to include the method-override library. This lets us also use PUT, PATCH and DELETE in our express application.

The first step, as always is to install the package.

npm install method-override

Once installed, we need to add some logic to our app.js.

var methodOverride = require('method-override');

app.use(methodOverride(function (req, res) {
    if (req.body && typeof req.body === 'object' && '_method' in req.body) {
        var method = req.body._method
        delete req.body._method
        return method
    }
}))

This middleware function will basically check to see if the post data contains a "_method" variable. If it does, then we will delete the method and reassign it to the real method.The idea is to smuggle the more descriptive method inside a POST request.

Now we can do something like the following.

<form method="POST" action="/post/<?=article.id?>"
    onsubmit="return confirm('Are you sure?');">
    <input type="hidden" name="_method" value="DELETE">
    <button type="submit">Delete</button>
</form>

And finally, we can now use the delete event to handle deletes.

router.delete('/post/:id', async function(req, res, next) {
    await db.Post.destroy({ where: { id: req.params.id} });
    res.redirect("/admin/articles");
});