Angular 5.0.0 HttpClient不会在POST上发送Headers

时间:2018-02-11 21:43:45

标签: angular5

当我使用HttpClient发送GET时,服务器会收到授权标头。但是当我使用POST发送相同的请求时,Angular不会发送授权标题。

let cabecalho1 = new HttpHeaders();

cabecalho1 = cabecalho1.append("Authorization", "Basic YXBpOmViYzg3Njg5MjhiZjkljjE1NGIyMTg4NGZlMjU5MDA3NDllMGU0MTRmZGM");
cabecalho1 = cabecalho1.append("Content-Type", "application/x-www-form-urlencoded");

let url = "http://localhost/ionic/json.php";

// 'post' doesn't sends Authorization Header.
// when I change to 'get' verb, the server receives the Authorization Header.
this.httpClient.post(url, 
  {
    headers: cabecalho1,

    params: {
      ola: 'mundo',
      cnt: '5'
    }
  }).subscribe(res => {
    // this.posts = res;
    console.log("resposta POST:");
    console.log(res);
  });

比较发送的POST与GET数据(黄色是GET)

In YELLOW, The GET sent the Authorization

当我使用Postman时,我的PHP服务器中的GET和POST都会收到授权标题。 为什么Angular 5 HttpClient 专门在POST中发送授权标头?

2 个答案:

答案 0 :(得分:1)

如果您查看HttpClient here的引用,您会发现get()的签名是这样的:

get(
    url: string,
    options: 
        { 
            headers?: HttpHeaders | { [header: string]: string | string[]; }; 
            observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; };
            reportProgress?: boolean; responseType?: "arraybuffer" | "blob" | "text" | "json"; withCredentials?: boolean;
        } = {}
 ): Observable<any>

,post()的签名是这样的:

post(
    url: string,
    body: any,
    options:
        {
            headers?: HttpHeaders | { [header: string]: string | string[]; };
            observe?: HttpObserve; params?: HttpParams | { [param: string]: string | string[]; };
            reportProgress?: boolean; responseType?: "arraybuffer" | "blob" | "text" | "json";
            withCredentials?: boolean;
        } = {}
): Observable<any>

如您所见,post()方法的“ body”参数不是可选的(因为它紧随其后没有'?'),因此是必需的。您正在发送标头,但标头位于发布请求的正文中,使它们无用。

要解决此问题,请为“ body”参数添加一个空对象,如下所示:

this.httpClient.post(url, {},
  {
    headers: cabecalho1,

    params: {
             ola: 'mundo',
             cnt: '5'
  }
}).subscribe(res => {
    // 
});

答案 1 :(得分:0)

试试这个:

  myApiFunction(id: string) {

    // add authorization header with jwt token
    let headers = new HttpHeaders({ 'Authorization': 'Bearer ' + this.token });
    let options = { headers: headers };

    return this.http.post(this.baseUrl + 'https://213.121.21.21/api/myApiFunction', id , options);
  }