我按照 Heroku 的本教程进行了 MEAN 堆栈 CRUD 应用程序部署。 创建、删除和获取所有工作。 我现在收到的唯一错误来自 Put。 我在尝试更新对象时收到 500 错误,但不确定原因。 我的代码如下。
//HTML
<div *ngIf="contact" class="row">
...
<button class="btn btn-info" *ngIf="contact._id" (click)="updateContact(contact)">Update</button>
//.ts file
updateContact = (contact: Contact) => {
var idx = this.getIndexOfContact(contact._id);
if (idx !== -1) {
this.contacts[idx] = contact;
this.selectContact(contact);
}
return this.contacts;
}
private getIndexOfContact = (contactId: String) => {
return this.contacts.findIndex((contact) => {
return contact._id === contactId;
});
}
//server.js file
app.put("/api/contacts/:id", function(req, res) {
var updateDoc = req.body;
delete updateDoc._id;
db.collection(CONTACTS_COLLECTION).updateOne({_id: new ObjectID(req.params.id)}, updateDoc, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to update contact");
} else {
updateDoc._id = req.params.id;
res.status(200).json(updateDoc);
}
});
});
我的控制台告诉我,在updateContact,联系人=未定义。但是,这绝对是因为我可以在我的删除和获取请求中控制台记录它。 之后我也收到 500 错误。他们的示例站点也不允许更新。看起来他们也得到了 500 错误。
哪个updateContact
是未定义的?您是否尝试过在每个方法的开头记录它?我们能看到你的ContactDetailComponent
吗?一旦您找到了解决方案,请发布答案,以便将来的询问者能够从中获得帮助。
编辑:意思是评论,错误的按钮。请忽略。
修复了此处的放置请求。 需要将正确的参数发送到 updateOne(( 方法并使用$set
app.put("/api/contacts/:id", function(req, res) {
var updateDoc = req.body;
delete updateDoc._id;
var newValues = { $set: updateDoc};
db.collection(CONTACTS_COLLECTION).updateOne({_id: new
ObjectID(req.params.id)}, newValues, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to update contact");
} else {
updateDoc._id = req.params.id;
res.status(200).json(updateDoc);
}
});
});