我在 Angular2 TypeScript 中有这段代码,我试图在其中添加如下所示的 header 。
['access-token', localStorage.getItem( 'token' )],
['client', localStorage.getItem( 'client' )],
['uid', localStorage.getItem( 'email' )],
['withCredentials', 'true'],
['Accept', 'application/json'],
['Content-Type', 'application/json' ]
发送请求时,我看不到请求中的 header 。 我正在处理跨域设置。还有其他方法吗?
private _request(url: string | Request, options?: RequestOptionsArgs) : Observable<Response> {
let request:any;
let reqOpts = options || {};
let index:any;
if(!reqOpts.headers) {
reqOpts.headers = new Headers();
}
for( index in this._config.authHeaders ) {
reqOpts.headers.set( this._config.authHeaders[index][0], this._config.authHeaders[index][1] );
}
request = this.http.request(url, reqOpts);
return request;
}
最佳答案
如果您的请求是跨域请求,则适用 CORS 概念。您可以查看这些链接以获取更多详细信息:http://restlet.com/blog/2015/12/15/understanding-and-using-cors/和 http://restlet.com/blog/2016/09/27/how-to-fix-cors-problems/ .当然,正如 Günter 所说,服务器端需要做一些事情来返回 CORS header 以允许您的浏览器处理响应。
这是一个在 HTTP 请求中添加 header 的示例服务:
export class MyService {
constructor(private http:Http) {
}
createAuthorizationHeader(headers:Headers) {
headers.append('Authorization', 'Basic ' +
btoa('a20e6aca-ee83-44bc-8033-b41f3078c2b6:c199f9c8-0548-4be7-9655-7ef7d7bf9d33'));
}
getCompanies() {
var headers = new Headers();
this.createAuthorizationHeader(headers);
return this.http.get('https://angular2.apispark.net/v1/companies/', {
headers: headers
}).map(res => res.json());
}
编辑
我刚刚看到您尝试设置 withCredential
header 。我认为你混合了不同的东西。 withCredentials
不是标准 header ,但 XHR JavaScript 对象上有一个 withCredentials
属性。请参阅此链接:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials .这应该在不使用 withCredentials
自定义 header 的情况下工作。
提醒一下,如果您想使用自定义 header ,您需要在服务器端的 Access-Control-Allow-Headers
header 中添加它。
希望对你有帮助, 蒂埃里
关于Angular2 http.request 无法添加 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34916623/