我对如何在Angular 5中为简单的Get请求创建一个好标头感到困惑。
这是我到目前为止所做的:
getUserList(): Observable<UserList[]> {
const headers = new Headers();
let tokenParse = JSON.parse(this.token)
headers.append('Authorization', `Bearer ${tokenParse}`);
const opts = new RequestOptions({ headers: headers });
console.log(JSON.stringify(opts));
const users = this.http.get<UserList[]>(this.mainUrl, opts)
return users
.catch(this.handleError.handleError);
}
这是我的console.log中的响应:
{"method":null,"headers":{"Authorization":["Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImYwODZlM2FiYTk0ZjVhMjVmNDhiNzlkYmI2YWUwOWY4YzE2MTUyMzg2N2I5MDZiY2MzNWQyNWJiYTZmYTE4YjEwZjA1MjZiNThkZjE2Y2FjIn0.eyJhdWQiOiJmMDExY2M1OC00MGNlLTQzYTktOGY3MS04NDI0OTRlM2E5OTciLCJqdGkiOiJmMDg2ZTNhYmE5NGY1YTI1ZjQ4Yjc5ZGJiNmFlMDlmOGMxNjE1MjM4NjdiOTA2YmNjMzVkMjViYmE2ZmExOGIxMGYwNTI2YjU4ZGYxNmNhYyIsImlhdCI6MTUyMzU1MTQ0NSwibmJmIjoxNTIzNTUxNDQ1LCJleHAiOjE1MjM1NTQ0NDUsInN1YiI6IjIiLCJzY29wZXMiOlsiYXV0aGVudGljYXRlZCIsImFuZ3VkcnUiXX0.E-WdQTl7nPDW0gj0rohfql-QgnAinzvDxPR-pySMrG07XFY9tA6Ex7IL23pDBmKDmQO8RcZKa0L5r6SRQq9_iqzMWzn5Zxp94J9TJrpZ2KGMoLR_FbK_tpC5G5q5vUnCe3q34sH7cPdT_2cI704OWWaYmIUKKpXWUIG0PJw_uKSJ_uOifPv59RZGQkoaQ9gPywDKe-uamm1Faug-Kk2YnFMoEJq7ou19zyxgdpX80ZTPUae67uB0PGLRuvxfGaqVsJ8k0NunAY3-pyUnBwR_3eeuOxf4TyfW2aiOJ9kuPgsfV4Z1JD7nMpNtTHMJaXEyNkBW8RlYHD1pj4dkdnsDmw"]},"body":null,"url":null,"withCredentials":null,"responseType":null}
看起来很漂亮。但是给了我这个错误
GET http://druang.dd:8080/user-list?_format=json 403(禁止)
还有另一条线索要解决这个谜团。在Sublime文本中,如果我将鼠标放在opts
上,它会显示如下内容:
src / app / services / userlist.service.ts(33,59)中的错误:错误TS2345: 类型&#39; RequestOptions&#39;的论证不能分配给参数 键入&#39; {headers?:HttpHeaders | {[header:string]:string |串[]; };观察?:&#34;身体&#34 ;; params?:Ht ......&#39;。财产类型&#39;标题&#39; 是不相容的。 输入&#39;标题&#39;不能分配给&#39; HttpHeaders | {[header:string]:string |串[]; }&#39 ;. 输入&#39;标题&#39;不能分配类型&#39; {[header:string]:string |串[]; }&#39 ;. 类型&#39; Headers&#39;
中缺少索引签名
任何想法? 这是完整的Git repo 谢谢你的帮助!
答案 0 :(得分:12)
我建议您使用HTTPInteceptor来处理添加令牌。这是一篇很棒的文章:https://www.illucit.com/angular/en-angular-5-httpinterceptor-add-bearer-token-to-httpclient-requests/
-----另一种解决问题的方法。 -----
import { Http, Headers, Response } from '@angular/http';
getLoggedInUser(auth_token): Observable<any> {
const headers = new Headers({
'Content-Type': 'application/json',
'Authorization': auth_token
})
return this.http.get(apiUrl, { headers: headers })
}
不要忘记在你的组件中打电话和订阅。
答案 1 :(得分:4)
两件事:
headers.append(...)
不会改变header对象,因此您的授权标头不会被发送。您需要执行headers = headers.append(...)
尝试this.http.get<UserList[]>(this.mainUrl, { headers: headers });
答案 2 :(得分:3)
我使用了以下代码,并且有效
从'@ angular / common / http'导入{HttpClient,HttpHeaders};
getServerList(){
var reqHeader = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('mpManagerToken'))
});
return this.http.get<Server[]>(`${environment.apiUrl}/api/Servers/GetServerList`, { headers: reqHeader });
}
答案 3 :(得分:2)
在Angular 6和Angular 7中,此方法可用于拦截所有HTTP请求并添加承载令牌。
实施教程可在此处获得。 Youtube,此频道包含所有教程。
拦截器组件
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpUserEvent,
HttpEvent
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { UserService } from '../shared/user.service';
import { tap } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private router: Router) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (req.headers.get('No-Auth') === 'True') {
return next.handle(req.clone());
}
if (localStorage.getItem('userToken') != null) {
const clonedreq = req.clone({
headers: req.headers.set(
'Authorization',
'Bearer ' + localStorage.getItem('userToken')
)
});
return next.handle(clonedreq).pipe(
tap(
succ => {},
err => {
if (err.status === 401) {
// this.router.navigateByUrl('/login');
} else if ((err.status = 403)) {
// this.router.navigateByUrl('/forbidden');
// alert(err.localStorage.getItem('userToken'));
}
}
)
);
} else {
this.router.navigateByUrl('/login');
}
}
}
警卫队成员
import { Injectable } from '@angular/core';
import {
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot,
Router
} from '@angular/router';
import { Observable } from 'rxjs';
import { UserService } from '../shared/user.service';
import { ToastrService } from 'ngx-toastr';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private userService: UserService,
private toastr: ToastrService
) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): boolean {
if (localStorage.getItem('userToken') != null) {
const roles = next.data['roles'] as Array<string>;
if (roles) {
const match = this.userService.roleMatch(roles);
if (match) {
return true;
} else {
// tslint:disable-next-line: quotemark
this.toastr.info("You don't have access to this page");
this.router.navigate(['/login']);
// this.router.navigate(['/forbidden']);
return false;
}
} else {
return true;
}
}
this.router.navigate(['/login']);
return false;
}
}
将其添加到app.modules.ts
providers: [
ConfirmationDialogService,
UserService,
DoctorService,
{ provide: OwlDateTimeIntl, useClass: DefaultIntl },
{ provide: OWL_DATE_TIME_FORMATS, useValue: MY_MOMENT_FORMATS },
AuthGuard,
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
],
然后将守卫添加到路线
{
path: 'adminPanel',
component: AdminPanelComponent,
canActivate: [AuthGuard],
data: { roles: ['Admin'] }
},
答案 4 :(得分:1)
我不擅长编程,但尝试和失败 如果发现这个:
getUserList(): Observable<UserList[]> {
let tokenParse = JSON.parse(this.token)
// let myHeaders = new Headers();
// myHeaders.set('Authorization', `Bearer ${tokenParse}`);
// let options = new RequestOptions({ headers: myHeaders});
const users = this.http.get<UserList[]>(this.mainUrl, { headers:new HttpHeaders().append('Authorization', `Bearer ${tokenParse}`)})
// const users = this.http.get<UserList[]>(this.mainUrl, options);
return users
.catch(this.handleError.handleError);
}
如果我使用.set
或.append
,这并不重要,在一天结束时,它在两种情况下都有效......
我真的不知道发生了什么,所以,如果有人想在评论中解释,欢迎你...
答案 5 :(得分:0)
'Authorization': 'Bearer ' + access_token,
有效
答案 6 :(得分:-1)
@HassanRahman在get
请求,post
请求中显示它
import { HttpClient, HttpHeaders } from '@angular/common/http';
getServerList(){
postData = { your data }
var reqHeader = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('mpManagerToken'))
});
return this.http.get<Server[]>(`${environment.apiUrl}/api/Servers/GetServerList`, postData, { headers: reqHeader });
}