标头中没有令牌请求(获取)Angular 2

时间:2017-04-25 07:59:57

标签: angular http-headers cors token

我不明白为什么令牌无法在请求中传递。服务器(java)没有收到令牌。

服务(角度2) ...

    private authToken: string =  localStorage.getItem('auth_token');
  private headers = new Headers({"Content-Type": "application/json"});
  // private options = new RequestOptions({headers: this.headers});

  constructor(private http: Http) {
    this.headers.append("charset", "UTF-8");
    this.headers.append("X-auth_token", this.authToken)
  }

  getCommunes(territoryId: number): Observable<any>{
    return this.http
      .get(`${urlBase}/forms/api/territoires/${territoryId}/communes`, this.headers)
      .map(res => res.json())

  }

... 如果我使用&#34; RequestOptions&#34;它是一样的。

浏览器控制台

console screenshot

网络(请求标头中没有任何内容)

network screenshot

谢谢!

1 个答案:

答案 0 :(得分:1)

我的猜测是你没有正确使用RequestOptions。试试这个:

private authToken: string =  localStorage.getItem('auth_token');
private headers = new Headers({"Content-Type": "application/json"});

constructor(private http: Http) {
    this.headers.append("charset", "UTF-8");
    this.headers.append("X-auth-token", this.authToken)
}

getCommunes(territoryId: number): Observable<any> {
   let options: RequestOptions = new RequestOptions({
       headers: this.headers
   });

   return this.http
      .get(`${urlBase}/forms/api/territoires/${territoryId}/communes`, options)
      .map(res => res.json())

}

我还认为您应该使用标题名称X-auth-token(使用短划线,而不是下划线)