我刚刚完成设置Angular2令牌身份验证,并从我的文档看,应该在发送每个请求的头client
uid
expiry
和token
,但我注意到我总是在后端获得我的默认Sign In
响应。Angular2令牌不发送头
我的角度(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
我一直在寻找到如何预先考虑他们-every-单呼,但我认为Angular2令牌应该解决它作为this issue
我要对这个解释不当,或我将不得不使某种拦截器预先添加所有标题?
更新的代码
由于下面的评论,我意识到我需要传递的标头。我已经修改了它与下面的代码片段工作,但Angular2令牌应该自动发送头。我应该遵循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
@Aravind感谢你 - 这是一个完全公平的观点。我做到了,它没有传递'application'作为内容类型,覆盖默认值,但它仍然不会自动发送Angular2-Token头部。 – DNorthrup
你在上面的代码中设置'content-type'? – Aravind