LuisPinto LuisPinto - 3 months ago 9
Node.js Question

How to delete on express without specificate the whole route

I have a route like this on express

app.delete('/items/:id', function (req,res) {
...
})


When I try to send a delete request on:

http://localhost/items/10 I delete the item successfully.

However, if I try to send the delete to http://localhost/items I get Cannot DELETE /items

Why can't I access to app.delete when I don't specify the id?

Answer

Why can't I access to app.delete when I don't specify the id?

Because if you want that, you need to tell Express that the id is optional, like this:

app.delete('/items/:id?', function (req,res) {
...
})

This will match the following requests:

  • DELETE /items/123 (where req.params.id will be '123')
  • DELETE /items/ (where req.params.id will be undefined)
  • DELETE /items (where req.params.id will also be undefined)