繁体   English   中英

Angular2 http.request无法添加标头

[英]Angular2 http.request not able to add headers

我在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;
}

这是我的回复标题 在此输入图像描述

如果您的请求是跨域请求,则适用CORS概念。 您可以查看这些链接以获取更多详细信息: http//restlet.com/blog/2015/12/15/understanding-and-using-cors/http://restlet.com/blog/2016/09 / 27 /如何修复cors-problems / 当然,正如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());
  }

编辑

我刚看到您尝试设置withCredential标头。 我认为你混合了不同的东西。 withCredentials不是标准标题,但XHR JavaScript对象上有withCredentials属性。 请参阅此链接: https//developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials 这应该不使用withCredentials自定义标头。

提醒一下,如果要使用自定义标头,则需要在Access-Control-Allow-Headers标头中的服务器端添加它。

希望它对你有帮助,蒂埃里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM