【问题标题】:How to add Headers to http.get request in Angular2?如何在 Angular2 中向 http.get 请求添加标头?
【发布时间】:2017-02-21 04:49:08
【问题描述】:
   import {Http, Response, Headers}          from '@angular/http'; 

getHeroes (): Observable<Heros[]> {
        return this.http.get(this.heroesUrl,  {withCredentials: true}
        )
          .map(this.extractData)
          .catch(this.handleError);
      }

不要知道标题的来源和方式。

var myHeaders = new Headers();
myHeaders.append('Access-Control-Allow-Origin', '*')

它们是如何组合的?

【问题讨论】:

    标签: angular2-services


    【解决方案1】:

    这就是您需要向 http 请求添加标头的方式

    import {Headers, RequestOptions} from 'angular2/http';
    
    let body = JSON.stringify({ 'foo': 'bar' });
    let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
    let options = new RequestOptions({ headers: headers });
    
    return this.http.post(url, body, options)
                    .map(res =>  res.json().data)
                    .catch(this.handleError)
    

    【讨论】:

      【解决方案2】:

      //可以发送单个和多个header

      import { Http, Headers, RequestOptions } from '@angular/http';
      
      const Url = 'http://localhost:3000/';
      const headers = new Headers;
      const body = JSON.stringify(
      {
      title: "data" 
      });
      headers.append('Content-Type', 'application/json');
      headers.append('Access-Control-Allow-Origin', '*');
      this.http.post(Url, body, { headers: headers })
      .pipe(map(res => res))
      .catch(err => err);
      
      // HttpHeaders in angular 5
      
      import { HttpHeaders } from '@angular/common/http';
      
      let header = new HttpHeaders();
      header.set('Content-Type', 'application/json');
      

      【讨论】:

        猜你喜欢
        • 2017-12-19
        • 1970-01-01
        • 1970-01-01
        • 2017-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多