【问题标题】:How to do a proper http post call in Angular 2?如何在 Angular 2 中进行正确的 http post 调用?
【发布时间】: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 脚本并尝试来自控制台的请求 :)

标签: node.js http angular


【解决方案1】:

您必须添加 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);
  }

【讨论】:

  • 我已经尝试过了,当浏览器尝试执行请求时出现错误。我在 OP 中添加了截图。
【解决方案2】:

我需要像 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。这两件事解决了这个问题。

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    相关资源
    最近更新 更多