当前,我在组件.ts文件中使用了此静态代码,但该代码不起作用。它返回未经授权的(401)。但是当我将令牌作为查询字符串传递时,它可以正常工作。请提供.ts文件组件的工作示例。
import { HttpClient, HttpResponse ,HttpHeaders} from '@angular/common/http';
var t=`eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODAwMFwvYXBpXC9sb2dpbiIsImlhdCI6MTUzNzcxNTMyNSwiZXhwIjoxNTM3NzE4OTI1LCJuYmYiOjE1Mzc3MTUzMjUsImp0aSI6IlBKWVhnSkVyblQ0WjdLTDAiLCJzdWIiOjYsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.1vz5lwPlg6orzkBJijsbBNZrnFnUedsGJUs7BUs0tmM`;
var headers_object = new HttpHeaders();
headers_object.append('Content-Type', 'application/json');
headers_object.append("Authorization", "Bearer " + t);
const httpOptions = {
headers: headers_object
};
this.http.post(
'http://localhost:8000/api/role/Post', {limit:10}, httpOptions
).subscribe(resp => {
this.roles = console.log(resp)
}
);
答案 0 :(得分:7)
添加AuthInterceptor
,它将拦截您的所有http请求并将令牌添加到其标头中:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.token; // you probably want to store it in localStorage or something
if (!token) {
return next.handle(req);
}
const req1 = req.clone({
headers: req.headers.set('Authorization', `Bearer ${token}`),
});
return next.handle(req1);
}
}
然后将其注册到您的AppModule
:
@NgModule({
declarations: [...],
imports: [...],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
],
bootstrap: [ AppComponent ],
})
export class AppModule { }
有关拦截器的更多信息:
https://angular.io/guide/http#intercepting-requests-and-responses
答案 1 :(得分:2)
您的代码存在的问题是HttpHeaders
类是不可变的,因此,当您调用append
时,它实际上会返回具有指定值的新实例,但不会修改原始对象。
尝试一下
var headers_object = new HttpHeaders().set("Authorization", "Bearer " + t);
默认情况下,HttpClient
将Content-Type设置为json
如果您需要在所有API调用中发送一个Authorization令牌,那么最好按照Martin的建议使用拦截器
答案 2 :(得分:0)
请像这样创建HttpHeaders对象(而不是添加),
var t="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODAwMFwvYXBpXC9sb2dpbiIsImlhdCI6MTUzNzcxNTMyNSwiZXhwIjoxNTM3NzE4OTI1LCJuYmYiOjE1Mzc3MTUzMjUsImp0aSI6IlBKWVhnSkVyblQ0WjdLTDAiLCJzdWIiOjYsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.1vz5lwPlg6orzkBJijsbBNZrnFnUedsGJUs7BUs0tmM";
var headers_object = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': "Bearer "+t)
});
const httpOptions = {
headers: headers_object
};
this.http.post(
'http://localhost:8000/api/role/Post', {limit:10}, httpOptions
).subscribe(resp => {
this.roles = console.log(resp)
}
);
答案 3 :(得分:0)
import { Injectable } from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs';
/** Pass untouched request through to the next request handler. */
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
return next.handle(req);
}
}
拦截器能够在标头中添加令牌
通过URL贝娄 https://angular.io/guide/http#intercepting-requests-and-responses
答案 4 :(得分:0)
另一种解决方案是使用angular-jwt:issue
无需创建拦截器,只需更新您的AppModule:
import { JwtModule } from "@auth0/angular-jwt";
import { HttpClientModule } from "@angular/common/http";
export function tokenGetter() {
return localStorage.getItem('access_token');
}
@NgModule({
declarations: [
AppComponent
],
imports: [
HttpClientModule,
JwtModule.forRoot({
config: {
tokenGetter: tokenGetter,
allowedDomains: ['localhost:3000', 'example.com'],
disallowedRoutes: ["http://example.com/examplebadroute/"],
authScheme: "Bearer " // Default value
}
})
],
bootstrap: [AppComponent]
})
export class AppModule { }
使用Angular的HttpClient发送的任何请求将自动具有一个 令牌作为授权标头附加。