How I add Headers to http.get or http.post in Typescript and angular 2?

后端 未结 4 2069
后悔当初
后悔当初 2020-12-16 11:35
getHeroes (): Observable {
    return this.http.get(this.heroesUrl)
      .map(this.extractData)
      .catch(this.handleError);
  }

4条回答
  •  借酒劲吻你
    2020-12-16 12:03

    You can define a Headers object with a dictionary of HTTP key/value pairs, and then pass it in as an argument to http.get() and http.post() like this:

    const headerDict = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Access-Control-Allow-Headers': 'Content-Type',
    }
    
    const requestOptions = {                                                                                                                                                                                 
      headers: new Headers(headerDict), 
    };
    
    return this.http.get(this.heroesUrl, requestOptions)
    

    Or, if it's a POST request:

    const data = JSON.stringify(heroData);
    return this.http.post(this.heroesUrl, data, requestOptions);
    

    Since Angular 7 and up you have to use HttpHeaders class instead of Headers:

    const requestOptions = {                                                                                                                                                                                 
      headers: new HttpHeaders(headerDict), 
    };
    

提交回复
热议问题