簡體   English   中英

Angular 5不包含http請求的標頭

[英]Angular 5 doesn't include headers to http request

我正在嘗試非常簡單的角度5 http'GET'請求。 當我檢查Chrome開發者工具時,我看不到http標頭。

import { HttpClient, HttpHeaders } from '@angular/common/http';
   // ...

   const headers = new HttpHeaders(
      {
        'Authorization': 'Basic ' + btoa(user.username + ':' + user.password)
      }
    );
    this.http.get('xyz-url', { headers }).subscribe((data: any) => {
      // do something
    });

我建議您為此創建攔截器:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  // ...

  public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    request = request.clone({
      setHeaders: {
        Authorization: 'Basic ' + btoa(user.username + ':' + user.password)
      }
    });
    return next.handle(request);
  }
  // ...
}

您可以在“網絡標簽”中看到

在此處輸入圖片說明

將標題設置為header屬性

this.http.get('xyz-url', { headers : headers }).subscribe((data: any) => {
  // do something
});

另外,檢查“ network標簽以查看請求的詳細信息,例如標題。

嘗試這個。

從'@ angular / common / http'導入{HttpHeaders};

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })
};

this.http.get('xyz-url', { httpOptions }).subscribe((data: any) => {
      // do something
});

此處閱讀有關添加HTTP標頭的更多信息

我認為它可以解決您的問題

  import {
        HttpClient,
        HttpRequest,
        HttpHeaders
    } from '@angular/common/http';

@Injectable()
export class HttpService {

    constructor(private httpClient: HttpClient) {
    }
       /**
        * Request options.
        * @param headerOptions
        * @returns {RequestOptionsArgs}
        */

        private requestOptions(headerOptions?: any): any {
            let options = {
                        headers: new HttpHeaders({
                            "Authorization": "Bearer " + 
                             this.session.get('token),
                            "Content-Type": "application/json"
                        })
                    }

            } 
            return options;
        }
/**
     * This method is use for send GET http Request to API.
     * @param url - Additional request URL.
     * @param body - params.
     * @param options  - Header(s) which will pass with particular request.
     */
    get(url: string, options?: any): Observable<any> {

        return this.httpClient.get(url, this.requestOptions(options))
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM