[英]Angular2 HTTP request not appending headers
In my application, I am trying to send a quick test request to my API to test my authentication. 在我的应用程序中,我试图向我的API发送快速测试请求以测试我的身份验证。 When a button is clicked, this function is called, which creates an Authorization header and makes an HTTP request:
单击按钮后,将调用此函数,该函数创建一个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);
});
}
However, when I'm debugging (or analyzing traffic using Fiddler), headers
has the header that I created, but nothing is being appended to the Http request. 但是,当我调试(或使用Fiddler分析流量)时,
headers
具有我创建的标头,但是没有任何内容附加到Http请求中。
You have to use RequestOptions
and append header to. 您必须使用
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);
});
Take a look at: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials 看看: https : //developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
If you are making a CORS request, you need to add the "withCredentials: true" RequestOption with the HTTP request. 如果要发出CORS请求,则需要在HTTP请求中添加“ withCredentials:true” RequestOption。 Otherwise, authorization headers will not be added with the request.
否则,授权标头将不会与请求一起添加。
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);
});
}
You also need to make sure that your server will accept the Authorization header by adding an "Acess-Control-Allow-Credentials = true" header to the pre-flight response, though this is different from server to server. 您还需要通过在飞行前响应中添加“ Acess-Control-Allow-Credentials = true”标头来确保服务器将接受Authorization标头,尽管这在服务器之间是不同的。 Also, make sure CORS is enabled on the server as well.
另外,还要确保在服务器上也启用了CORS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.