任何想法如何将标题添加到下面显示的函数中?我创建了登录服务,我得到了响应状态200.但是当我尝试发送GET请求时,我得到了Failed to load resource: the server responded with a status of 403 (Forbidden).
func() {
return this.http.get('/data', )
.map(response => response.json())
.subscribe(response2 => this.response2 = response2);
}
我的GET:
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
return super.get(appConfig.apiUrl + url, this.addJwt(options)).catch(this.handleError);
}
private addJwt(options?: RequestOptionsArgs): RequestOptionsArgs {
// ensure request options and headers are not null
options = options || new RequestOptions();
options.headers = options.headers || new Headers();
// add authorization header with jwt token
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser && currentUser.token) {
options.headers.append('Authorization', 'Bearer ' + currentUser.token);
}
return options;
}
解
问题是后端期望令牌以Token 132083128901302
的形式发送,但我发送Bearer 132083128901302
。将Bearer更改为令牌后,一切正常。
答案 0 :(得分:0)
let headers = new Headers({ 'Authorization': 'Bearer ' + jwt });
let options = new RequestOptions({ headers: headers });
return this.http.get('http://test.dev/get/user', options).map(res => res.json());
我强烈建议您通过HttpClient模块使用拦截器。它易于实现,应用程序中的代码更少,更易于管理。