【发布时间】:2016-08-28 22:03:44
【问题描述】:
我从 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 进行 post 调用时,一切正常,但在 Angular 2 中,我似乎无法理解 body 参数。这是如何以正确的方式完成的?我尝试了很多方法,但都没有奏效。
我尝试在选项中添加标题,但这并没有解决问题:
【问题讨论】:
-
我会尝试使用 jQuery ajax 或直接使用简单的 javascript 请求来执行此操作,以确保一切正常,因为 angular2 代码看起来不错,我看到你得到 404 not found 这意味着服务器问题。
-
我可以只导入 jquery ajax 库吗?
-
啊,确实,将 jQuery 与 angulr 一起使用有点棘手。不,遗憾的是你不能只导入它:stackoverflow.com/questions/30623825/…。但是您可以在 HTML 标头中添加 jQuery 脚本并尝试来自控制台的请求 :)