【发布时间】:2018-01-28 16:42:18
【问题描述】:
我刚刚完成了 Angular2-Token 身份验证的设置,从我在文档中看到的内容来看,它应该在每个请求的标头中发送 client uid expiry 和 token,但我注意到了我总是在后端收到默认的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 client 和uid,它的身份验证没问题。
当我检查网络时,我没有看到请求中传递的标头。
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