[英]How to do a proper http post call in Angular 2?
I'm starting out with Angular 2 and I want to do a post call to my node.js server to update data. 我从Angular 2开始,我想对我的node.js服务器进行后期调用以更新数据。 This is the code in my service: 这是我服务中的代码:
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);
}
My API route code: 我的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
);
});
});
}
When I do a post call with postman, everything works fine, but in Angular 2 I don't seem to get the body parameter across. 当我与邮递员进行邮递时,一切正常,但是在Angular 2中,似乎没有传递body参数。 How is this done in a right way? 如何正确地做到这一点? I tried many things but none of them worked. 我尝试了很多东西,但没有一个起作用。
I tried adding the headers in the options but that didn't resolve the problem: 我尝试在选项中添加标题,但未能解决问题:
You have to add the content-type
header. 您必须添加content-type
标头。
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);
}
I needed to add the headers as rgvassar said: 我需要添加标头,如rgvassar所说:
let body : string = JSON.stringify({ "firstName" : firstName, "lastName" : lastName});
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: Response) => res)
But there was also a CORS problem on my API (made with Keystonejs), because I send a header with the request, I needed to allow the OPTIONS on CORS. 但是我的API(由Keystonejs制作)上也存在一个CORS问题,因为我随请求发送了标头,因此我需要允许对CORS进行操作。 This 2 things resolved the issue. 这两件事解决了问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.