【问题标题】:Angular2-Token not sending headersAngular2-Token 不发送标头
【发布时间】:2018-01-28 16:42:18
【问题描述】:

我刚刚完成了 Angular2-Token 身份验证的设置,从我在文档中看到的内容来看,它应该在每个请求的标头中发送 client uid expirytoken,但我注意到了我总是在后端收到默认的Sign In 响应。

我的 Angular(4) 服务很简单。

export class ClientService {

  constructor(private http: Http) { }

  private clientsUrl = 'baseUrl/clients';

  getClients() : Observable<Client[]> {
    return this.http.get(this.clientsUrl)
      .map((res: Response) => res.json())
      .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

  };

在组件中:

export class ClientComponent implements OnInit {

  constructor(private clientService: ClientService) { }
  clients: Client[];

  ngOnInit() {
    this.getClients();
  }

  getClients() {
    this.clientService.getClients()
      .subscribe(
        clients => this.clients = clients,
        err => {
          console.log(err);
        }
      );
  }

}

我还有一个包含时间戳 + ID 的通用模型,因为我不确定它将如何处理响应。

export class Client {
  constructor(
    id: number,
    name: string,
    status: string,
    logo: string,
    user_id: number,
    created_at: Date,
    updated_at: Date
  ){}
}

我已经在 POSTMAN 中测试了端点,并且响应符合我的预期。我在标题中发送access_token clientuid,它的身份验证没问题。

当我检查网络时,我没有看到请求中传递的标头。

GET /clients HTTP/1.1
Host: baseUrl
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/plain, */*
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36
Referer: http://localhost:8080/clients
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8

我正在研究如何将它们添加到每个调用中,但我认为 Angular2-Token 应该可以解决它,如 this issue 中所述

我是不是处理不当,还是我必须制作某种拦截器来添加所有标题?

更新代码

感谢下面的评论,我意识到我需要传递标题。我已经修改它以使用下面的 sn-p,但 Angular2-Token 应该自动发送标头。我应该遵循 JWT-Token 逻辑还是 Angular2-token?

 getClients() : Observable<Client[]> {
let headers = new Headers({
  'Content-Type': 'application',
  'access-token': localStorage.getItem('accessToken'),
  'client': localStorage.getItem('client'),
  'uid':localStorage.getItem('uid')
});
let options = new RequestOptions({ headers: headers});

return this.http.get(this.clientsUrl, options)
  .map((res: Response) => res.json())
  .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

};

【问题讨论】:

  • 您在 http 调用 this.http.get(this.clientsUrl,options) 中缺少 RequestOptions 您应该将令牌添加到标头
  • @Aravind 谢谢你 - 这是一个完全公平的观点。我做到了,它没有将“应用程序”作为内容类型传递,覆盖了默认的,但是它仍然没有按应有的方式自动发送 Angular2-Token 标头。
  • 在上面的代码中你在哪里设置content-type??
  • @Aravind 在您评论我如何更改代码后,我更新了我的问题。

标签: angular access-token


【解决方案1】:

对于遇到此问题的任何人,我的问题是我没有使用 Angular2-Token 提供的 HTTP Wrapper

这实际上让我非常容易确保正确的标记,并且没有重复的标题。

  constructor(private authToken: Angular2TokenService) {
  }

  getClients(): Observable<Client[]> {
    return this.authToken.get('clients')
      .map(res => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  };

  addClient(client:Client): Observable<Client> {
    return this.authToken.post('clients', client)
      .map(res => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

  getClientById(id): Observable<Client> {
    return this.authToken.get('clients/' + id)
      .map(res => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

  deleteClient(id): Observable<Client> {
    return this.authToken.delete('clients/' + id)
      .map(res => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

  editClientById(client:any): Observable<Client> {
    return this.authToken.patch('clients/' + client.id, client)
      .map(res => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

只要您有init 中所述的baseApi,这将简化流程。

【讨论】:

    【解决方案2】:

    在您的 options 中将 withCredentials 设置为 true

    let options = new RequestOptions({ headers: headers});
    options.withCredentials = true;///////////////////add this
    

    也一个接一个地附加你的标题

        let headers = new Headers({ 'Content-Type': 'application', });
        headers.append('access-token', localStorage.getItem('accessToken'));
        headers.append('client', localStorage.getItem('client'))
        headers.append('uid', localStorage.getItem('uid'))
    

    【讨论】:

      猜你喜欢
      • 2017-05-14
      • 2018-10-23
      • 2018-01-17
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 2018-12-05
      • 2016-06-17
      • 1970-01-01
      相关资源
      最近更新 更多