Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

前端 未结 9 1071
孤街浪徒
孤街浪徒 2020-11-22 05:45

Here is my code:

import { HttpClient, HttpErrorResponse, HttpHeaders } from \'@angular/common/http\';
9条回答
  •  孤城傲影
    2020-11-22 06:17

    The instances of the new HttpHeader class are immutable objects. Invoking class methods will return a new instance as result. So basically, you need to do the following:

    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json; charset=utf-8');
    

    or

    const headers = new HttpHeaders({'Content-Type':'application/json; charset=utf-8'});
    

    Update: adding multiple headers

    let headers = new HttpHeaders();
    headers = headers.set('h1', 'v1').set('h2','v2');
    

    or

    const headers = new HttpHeaders({'h1':'v1','h2':'v2'});
    

    Update: accept object map for HttpClient headers & params

    Since 5.0.0-beta.6 is now possible to skip the creation of a HttpHeaders object an directly pass an object map as argument. So now its possible to do the following:

    http.get('someurl',{
       headers: {'header1':'value1','header2':'value2'}
    });
    

提交回复
热议问题