简体   繁体   中英

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?

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 )

As in express routing mechanism request is deals for POST , GET , PUT , DELETE ,it expects the resource in your server .

when you first define route

`http://localhost/items/10`  it matches the request with your route that expect

parameter then it find the resource and delete it

As compared to other http://localhost/items It assume different resource and not perform or hitting that resource

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM