繁体   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