我想访问在数据库中发布一些数据的api。对于api身份验证,我使用jwt令牌。我在将jwt令牌放入我的请求的头部时遇到了问题。
我正在使用aws api,它调用了一个lambda函数,它可以访问我的数据库,并且angular用于前端。
我的语言代码是:
const request = {
"header": new HttpHeaders({
'Authorization': 'Bearer '+myVariables.jwt,
}),
"body": {
... //body part works
}
}this.http.post(this.postBlogUrl, request).subscribe(
res => {console.log("data posted to api"); window.location.reload();},
err => {console.log("Error occured: " + err.message);}
);myVariable.jwt是一个导出的变量,当他们登录时,我将在其中保存已签名用户的jwt令牌。
this.postBlogUrl是指向我的api的url链接。
同样奇怪的是,当我尝试console.log(request.header)时,我看不到console.log(request.header);给我的授权字段:console.log result
当我在POSTMAN中尝试同样的事情时,我在" header“部分而不是在request对象中指定了header授权,它工作得很好。那么我怎样才能在我的angular应用程序中做同样的事情呢?
那么,我如何才能像postman https://imgur.com/a/Qk7P7D3中那样指定报头,而不是将其包含在requst中呢?
发布于 2021-08-14 10:37:32
您应该使用HttpInterceptor
将中间件添加到http处理链的角度方法是HttpInterceptor。
您基本上编写了一个带有intercept()方法的类:
@Injectable()
export class HeadersInterceptor implements HttpInterceptor {
public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headers = req.headers.append('Authorization', myData);
return next.handle(req.clone({ headers }));
}然后使用HTTP注入令牌注入它。
发布于 2021-08-14 10:41:27
我认为你有一个拼写错误的header而不是headers
https://stackoverflow.com/questions/68782271
复制相似问题