gpt4 book ai didi

javascript - NodeJS/Angular 无法删除对象

转载 作者:行者123 更新时间:2023-12-03 08:17:16 36 4
gpt4 key购买 nike

我正在尝试删除 MongoDB 数据库/NodeJS 上的对象。它在休息客户端上工作,但在 Angular 上使用删除项目的按钮不起作用。每次我在 REST 客户端上测试它时,它都工作正常,但在 Angular 上却不起作用。

我该如何修复它才能使其正常工作?下面是我的代码:

//still need to resolve the delete function
//still need to resolve the delete function
$scope.remove = function(item) {
itemid = $scope.item.id;

console.log(item.id);

$http({ url: "http://localhost:3000/api/book",
method: "DELETE",
data: "id="+item.id,
headers: {"Content-Type":"application/x-www-form-urlencoded"}

}).then(function(res) {
console.log(res.data);
console.log("good");
}, function(error) {
console.log(error);
console.log("bad");
});
}

我的 Node/Express 代码

//Delete an existing book
app.delete("/api/book", function(req, res){

res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
res.header("Access-Control-Allow-Methods", "DELETE");

Book.findOneAndRemove({ id: req.params.id}, function(err, result){
res.json({
message: "Successfully deleted the book",
book: result
});
});
});

最佳答案

params 对象位于 body 内部,因此您必须将端点更改为:

app.delete("/api/book/:isbn", function(req, res){
console.log('Client Reached the endpoint.');
Book.findOneAndRemove({ id: req.body.params._id}, function(err, result){
res.json({
message: "Successfully deleted the book",
book: result
});
});
});
<小时/>

建议

由于您没有使用 isbn,因此您应该将端点更改为:

app.delete( "/api/book/:id", function ( req, res ) {
Book.findOneAndRemove( { id: req.params.id }, function ( err, result ) {
res.json( {
message: "Successfully deleted the book",
book: result
} );
} );
} );

你的 Angular 函数将是:

//Updated
$scope.remove = function () {

$http( {
method: 'DELETE',
url: '/api/book/' + item.id //Verify if item.id has a value...
} ).then(
function ( response ) {
console.log( 'Sucess', response );
},
function ( response ) {
console.log( 'Fail', response )
}
);

};

记住以下几点

params: "/api/route/:param"
call: req.params.param

query strings(e.g. /api/route/1?somequery=something): "/api/route/:param"
call: req.query.somequery

data (e.g. {id: 1, name: 'x'}): "/api/route/:param"
call: req.body.id, req.body.name

关于javascript - NodeJS/Angular 无法删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33884693/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com