【发布时间】:2019-02-07 23:39:04
【问题描述】:
我尝试将我的数据从 Angular 更新到 Node.js
组件.ts
updatefunction(id,data){
console.log("component",data);
//component {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123@gmail.com", //username: "Test"}
this.uAdminService
.updateUser(id,data).subscribe(
result => {
//console.log(result.json());
},
error => {
console.log(error.json());
}
);
}
在 myservice.ts 中
updatefunction(id, data){
console.log("service", data);
//service {role: "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123@gmail.com", //username: "Test"}
let headers = new Headers({ 'x-access-token': this.token, 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
return this.http.put(this.url+id, data, options);
}
我的 nodejs 控制器
router.put('/:id', VerifyToken, function (req, res) {
console.log(req.body);
//{'{\n "role": "User", \n "_id": "5c2dc052d6bfba36b41b34dd" \n}'}
User.findByIdAndUpdate({_id:req.params.id}, req.body, {new: true}).select("-password")
.then(users => {
res.send(users);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while retrieving Report."
});
});
});
我的 req.body 控制台像这样 {'{\n "role": "User", \n "_id": "5c2dc052d6bfba36b41b34dd" \n}'} 但我以这种格式从 angularjs 传递 {role : "User", _id: "5c2dc052d6bfba36b41b34dd", name: "Test", email: "test123@gmail.com", //username: "Test"}
我不知道为什么它会转换,所以它不会更新到 db
如果我从 api 控制台它会喜欢这样 { name: "Test",email: "test123@gmail.com"}
【问题讨论】: