我刚开始使用 Angular 2,我想对我的 node.js 服务器进行后调用以更新数据。这是我服务中的代码:
updateEmployee(id : string, firstName? : string, lastName? : string){
let body : string = JSON.stringify({ "firstName" : "test", "lastName" : "testtwo"});
return this.http.post(this._employeesUrl + id, body)
.map(res => res.json())
.catch(this.handleError);
}
我的 API 路由代码:
exports.update = function(req, res) {
Employee.model.findById(req.params.id).exec(function(err, item) {
if (err) return res.apiError('database error', err);
if (!item) return res.apiError('not found');
console.log(req);
var data = (req.method == 'POST') ? req.body : req.query;
item.getUpdateHandler(req).process(data, function(err) {
if(req.body.firstName){
item.firstName = req.firstName;
}
if(req.body.lastName){
item.lastName = req.body.lastName;
}
if (err) return res.apiError('create error', err);
res.apiResponse(
200
);
});
});
}
当我与 postman 进行邮寄时,一切正常,但在 Angular 2 中,我似乎没有得到 body 参数。这是如何以正确的方式完成的?我尝试了很多东西,但没有一个奏效。
我尝试在选项中添加 header ,但这并没有解决问题:
最佳答案
您必须添加 content-type
header 。
updateEmployee(id : string, firstName? : string, lastName? : string){
let body : string = JSON.stringify({ "firstName" : "test", "lastName" : "testtwo"});
let headers = new Headers({ 'content-type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(this._employeesUrl + id, body, options)
.map(res => res.json())
.catch(this.handleError);
}
关于node.js - 如何在 Angular 2 中进行正确的 http post 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37011258/