简体   繁体   中英

express delete route not found

I am trying this code to delete specific record in mongo by id

where in angular I'm passing the Id from the controller It gives error code saying 404 not found code in Node server side file is :

app.delete('/contactlist/id', function (req, res) {
var id = req.params.id;
console.log("in delete"+ id);
db.contactlist.remove({id : mongojs.ObjectId(id)}, function ( err , doc){
    res.json(doc);
  });
});

and code in controller of angular :

    $scope.remove = function (id){
    console.log(id);
    $http.delete('/contactlist'+ id ).success( function(response) {
        refresh();
    });
}

Everything looks ok, except

$http.delete('/contactlist'+ id ) //you forgot additional slash, '/contactlist/'+ id
.success( function(response) {
    refresh();
});

And

app.delete('/contactlist/id', function (req, res) { //this must be a param '/contactlist/:id'
    var id = req.params.id;
    console.log("in delete"+ id);
    db.contactlist.remove({id : mongojs.ObjectId(id)}, function ( err , doc){
        res.json(doc);
    });
});

In summary

Add slash to $http.delete

$http.delete('/contactlist/'+ id).success( function(response) {
    refresh();
});

Make id param in your server.

app.delete('/contactlist/:id', function (req, res) { //colons are important
    var id = req.param.id;
    console.log("in delete"+ id);
    db.contactlist.remove({id : mongojs.ObjectId(id)}, function ( err , doc){
        res.json(doc);
    });
});

Try below code

 app.delete('/contactlist/:id', function (req, res) {
 var id = req.params.id;
console.log("in delete"+ id);
db.contactlist.remove({id : mongojs.ObjectId(id)}, function ( err , doc){
res.json(doc);
});
});

Your can see the doc from here to pass params with the url: http://expressjs.com/en/api.html

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