以角度2发送http帖子中的数据?

时间:2018-01-10 21:07:10

标签: javascript angular typescript ionic-framework http-headers

我正在尝试使用不同线程的http post发送数据,但我不能这样做。 我需要发送这些数据,并在邮递员中进行测试。

头。 内容类型:application / x-www-form-urlencoded 授权:基本用户:传递

体。 grant_type:密码 范围:个人资料

这是我的代码。

login() {

    let url = URL_LOGIN;

    let headers = new Headers(
      {
        'Content-Type': 'application/json',
        'Authorization': 'Basic user:pass'
      });

    let body = {
      'grant_type': 'password',
      'scope': 'profile'
    }

    return this.http.post(url, body, { headers: headers })
      .map((response: Response) => {
        var result = response.json();
        return result;
      })

  }

提前致谢!!

1 个答案:

答案 0 :(得分:1)

您需要修改两件事:

  1. 传入http post方法的标头错过了一步。它应包含以下内容:

    let options = new RequestOptions({ headers: headers });
    

    确保从RequestOptions

    导入@angular/http

    然后将options传递到您的post方法中,如下所示:

    return this.http.post(url, body, options)...
    
  2. http post方法体只能是一个字符串。因此,它应该如下:

    let body = 'grant_type=password' + '&scope=profile';