【问题标题】:Angular HttpClient blocking Authorization headerAngular HttpClient 阻塞授权标头
【发布时间】:2019-07-28 12:39:02
【问题描述】:

Angular HttpClient 似乎不发送标头。 我检查了网络调用(谷歌浏览器),我看到标题显示在请求有效负载部分,而不是显示在请求标题部分。 代码和网络调用截图附在下面。

服务:

submitproduct(url: string){
    const httpOptions = {
      headers: new HttpHeaders().set('Authorization','Token '+localStorage.getItem('token')),
      body: new HttpParams().set('url',url)
    };
    return this.httpClient.post(this.baseUrl + '/custom/products/', httpOptions);
  }

更新

将服务代码更改为

let headers = new HttpHeaders().set('Content-Type', 'application/json')
                                    .set('Authorization','Token '+token);
    return this.httpClient.post(this.baseUrl + '/custom/products/', product , {
      headers,
    })

仍然面临同样的问题,正在发送数据而没有发送标头。

我还为其中一个 API 尝试了 fetch 方法并且工作正常。


      fetch(baseUrl + '/auth/login-check/', {
          method: "GET",
          headers: new Headers({'Authorization': 'Token ' + token})
        }).then((response) => {
              return response.json();}) 
              .then((returnedData) => { 
                if (returnedData['success']){
                  this.logged_in = true;
                }
                else{
                  this.logged_in = false;
                }
            }).catch((error) => {
                console.log(JSON.stringify(error.message))
            });   
      }

选项标题

帖子标题

【问题讨论】:

  • post 的第二个参数是消息正文,而不是选项。 angular.io/guide/http#making-a-post-request
  • @R.Richards 我将代码更改为return this.httpClient.post(this.baseUrl + '/custom/products/',null , httpOptions); 仍然没有发送请求标头。改变的是我现在看不到请求有效负载。

标签: angular typescript httpclient


【解决方案1】:

HttpClient.post 期望第二个参数是 POST 请求的主体。您可以使用以下方法正确提供标题:

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'Token '+token
  })
};

return this.httpClient.post(this.baseUrl + '/custom/products/', product , httpOptions );

如果发送标题对象,如您的问题所示,您也可以使用{headers: headers}。见下文:

return this.httpClient.post(this.baseUrl + '/custom/products/', product , {
      headers: headers,
    })

【讨论】:

  • 我完全按照你说的做了,仍然没有发送标题,我尝试添加其他标题,当添加Origin时,我收到错误Refused to set unsafe header "Origin",这是有道理的,但是没有- 提示授权有什么问题。也重新检查了后端,但使用邮递员它工作正常。
  • 你的意思是 GET 调用的标头?
  • 我的意思是,同一请求的其他标头参数。
  • 我感觉,Authorization header 被 angular HttpClient 阻塞了。
猜你喜欢
  • 2018-02-04
  • 2018-08-28
  • 2019-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多