node.js - 如何在 Angular 2 中进行正确的 http post 调用?

标签 node.js http angular

我刚开始使用 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 ,但这并没有解决问题:

Error after adding headers

最佳答案

您必须添加 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/

相关文章:

javascript - 写入文本文件而不覆盖 fs Node js

php - 假设解码的百分比编码 URI 变成 UTF-8 是否安全?

java - 从应用注册中列出 Azure 存储帐户容器时,受众验证失败

http - angular2 – 多次处理相同的响应错误

javascript - 在 NodeJS 中,如何从虚拟函数中退出父函数

node.js - 通过我的应用程序在没有终端的情况下运行夜类?

angular - 此导入包含错误,可能会影响依赖于此 NgModule 的组件

javascript - 过滤范围之间的数据

javascript - 将可观察量转换为数组

node.js - 使用 socket.io、node.js 和 mongodb 更新服务器端的 ejs 变量