我剛剛完成設置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