Angular2 http.request无法添加标头

Angular2 http.request无法添加标头,angular,typescript,Angular,Typescript,我在Angular2 TypeScript中有这段代码,我试图添加如下标题 ['access-token', localStorage.getItem( 'token' )], ['client', localStorage.getItem( 'client' )], ['uid', localStorage.getItem( 'email' )], ['withCredentials', 'true'], ['Accept', 'application/json'], ['Content-Ty

我在Angular2 TypeScript中有这段代码,我试图添加如下标题

['access-token', localStorage.getItem( 'token' )],
['client', localStorage.getItem( 'client' )],
['uid', localStorage.getItem( 'email' )],
['withCredentials', 'true'],
['Accept', 'application/json'],
['Content-Type', 'application/json' ]
发送请求时,我看不到请求中的标题。 我正在进行跨域设置。还有别的办法吗

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;
}
private\u请求(url:string |请求,选项?:RequestOptionsArgs):可观察{
让我们请求:任何;
设reqOpts=options | |{};
let索引:任意;
如果(!请求标题){
reqOpts.headers=新标题();
}
for(此.u config.authHeaders中的索引){
requopts.headers.set(this._config.authHeaders[index][0],this._config.authHeaders[index][1]);
}
request=this.http.request(url,reqOpts);
返回请求;
}
这是我的回复标题

如果您的请求是跨域请求,那么CORS概念适用。您可以查看这些链接以了解更多详细信息:和。当然,正如Günter所说,服务器端需要做一些事情来返回CORS头,以允许浏览器处理响应

以下是在HTTP请求中添加头的示例服务:

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());
  }
编辑

我刚才看到您试图用credential设置
标题。我认为你混合了不同的东西
withCredentials
不是标准头,但XHR JavaScript对象上有一个
withCredentials
属性。请参阅此链接:。这应该可以在不使用带有凭据的
自定义标题的情况下工作

提醒您,如果要使用自定义标头,需要将其添加到服务器端的
Access Control Allow Headers
标头中

希望它能帮助你,
Thierry

您可能需要在服务器上配置
访问控制允许标头
。完成后,您可以看到我刚刚添加到帖子中的响应标头。谢谢当我使用this.http.get时,它给了我一个错误“飞行前响应中的访问控制允许标头不允许带有凭据的请求标头字段。”。我知道在CORS中调用了选项方法。http.get尝试在选项requestmissing
Access Control Allow Credentials:true
中设置标题。刚刚将响应标题添加到POST中。我根据您的问题编辑更新了我的答案。