gpt4 book ai didi

javascript - Angular 5 在使用 httpClient 发布之前将 token 添加到 header

转载 作者:行者123 更新时间:2023-11-28 13:01:20 24 4
gpt4 key购买 nike

我正在使用restapi,它要求我在创建新记录之前向 header 添加 token 。

现在我有一个服务来创建一个新记录,如下所示:

服务.ts

create(title, text) {
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
headers = headers.append('Authorization', token); // Not added yet as this is the reason for the question
return this.http.post('http://myapi/api.php/posts', {
title: 'added title',
text: 'added text'
}, { headers });
}

app.component.ts

add() {
this.service.create('my title', 'body text').subscribe(result => {
console.log(result);
});
}

这样做的问题是,它不允许我添加新记录,因为它需要 token ,为了获取 token ,我需要运行以下命令:

getToken() {
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
return this.http.post('http://myapi/api.php/user', {
username: 'admin',
password: 'password'
}, { headers });
}

我的问题是......我如何将这两个一起放入一个调用而不是两个......或者什么时候是执行此操作的最佳方法?

最佳答案

除了 @Pardeep Jain 已经提到的之外,您还可以为 HttpClient 添加一个拦截器(> Angular 版本 4,您提到您正在使用 5),它将自动为所有请求添加授权 header 。

如果您只需要对一个请求进行身份验证,最好保持简单并使用 Pardeep 的解决方案。

如果您希望对大多数请求进行身份验证,请添加拦截器。

模块,比如说app.module.ts

@NgModule({
//...
providers: [
//...
{
provide: HTTP_INTERCEPTORS,
useClass: JwtInterceptor,
multi: true
},
//...
]
//...
})

和你的jwt拦截器,比如说jwt.interceptor.ts

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private injector: Injector, private router: Router) {
}

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({
headers: req.headers.set('Authorization', /* here you fetch your jwt */this.getToken())
.append('Access-Control-Allow-Origin', '*')
});
return next.handle(authReq).do((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}, (response: HttpErrorResponse) => { });
}

getToken() {
let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
return this.http.post('http://myapi/api.php/user', {
username: 'admin',
password: 'password'
}, { headers });
}
}

如果您想阅读一些内容,请在此处阅读更多内容:https://medium.com/@ryanchenkie_40935/angular-authentication-using-the-http-client-and-http-interceptors-2f9d1540eb8

关于javascript - Angular 5 在使用 httpClient 发布之前将 token 添加到 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50132753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com