簡體   English   中英

Angular2 HTTP請求未附加標頭

[英]Angular2 HTTP request not appending headers

在我的應用程序中,我試圖向我的API發送快速測試請求以測試我的身份驗證。 單擊按鈕后,將調用此函數,該函數創建一個Authorization標頭並發出HTTP請求:

  public test() {
    const headers: Headers = new Headers();
    headers.append('Authorization', 'Bearer ' + this.auth.token);
    this.http.get('http://localhost:62940/api/ping/secure', { headers: headers }).subscribe(x => {
      console.log(x);
    });
  }

但是,當我調試(或使用Fiddler分析流量)時, headers具有我創建的標頭,但是沒有任何內容附加到Http請求中。

您必須使用RequestOptions並將標頭附加到。

let headers = new Headers();

headers.append('Authorization', 'Bearer ' + this.auth.token);
let options = new RequestOptions({headers: headers});
this.http.get(URL, options).subscribe(x => {
     console.log(x);
});

看看: https : //developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

如果要發出CORS請求,則需要在HTTP請求中添加“ withCredentials:true” RequestOption。 否則,授權標頭將不會與請求一起添加。

public test() {
   const headers: Headers = new Headers();
   headers.append('Authorization', 'Bearer ' + this.auth.token);
   this.http.get('http://localhost:62940/api/ping/secure', {
      withCredentials: true,
      headers: headers
   }).subscribe(x => {
       console.log(x);
   });
}

您還需要通過在飛行前響應中添加“ Acess-Control-Allow-Credentials = true”標頭來確保服務器將接受Authorization標頭,盡管這在服務器之間是不同的。 另外,還要確保在服務器上也啟用了CORS。

暫無
暫無

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

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