如何在Angular 2中进行正确的http post调用?
我刚开始使用Angular 2,我想对我的node.js服务器进行一个post调用来更新数据。 这是我服务中的代码:
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中,我似乎没有得到身体参数。 这是如何以正确的方式完成的? 我尝试了很多东西,但都没有工作。
我试图在选项中添加标题,但是没有解决问题:
您必须添加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); }
我需要添加标题为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)
但是我的API(使用Keystonejs)也存在一个CORS问题,因为我发送一个包含请求的头文件,我需要允许CORS上的OPTIONS。 这2件事情解决了这个问题。