【问题标题】:Angular2 http.request not able to add headersAngular2 http.request 无法添加标头
【发布时间】:2017-06-23 02:52:09
【问题描述】:

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

这是我的响应头

【问题讨论】:

  • 您可能需要在服务器上配置Access-Control-Allow-Headers
  • 已经完成,您可以看到我刚刚添加到帖子中的响应标头。谢谢

标签: angular typescript


【解决方案1】:

如果您的请求是跨域请求,则适用 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 标头以允许您的浏览器处理响应。

这是一个在 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 标头中。

希望对你有帮助 蒂埃里

【讨论】:

  • 当我使用 this.http.get 时,它给了我一个错误“在预检响应中 Access-Control-Allow-Headers 不允许使用带有凭据的请求标头字段。”。我知道在 CORS 中调用了 Options 方法。 http.get 尝试在选项请求中设置标头
  • 缺少Access-Control-Allow-Credentials: true
  • 刚刚将响应头添加到帖子中
  • 我根据您的问题编辑更新了我的答案。
猜你喜欢
  • 2015-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-02
  • 2019-08-17
  • 2020-08-24
  • 2020-03-27
  • 1970-01-01
相关资源
最近更新 更多