我正在开发一个项目,该项目使用 Cognito 作为身份验证服务来保护使用 nodeJS 制作的无服务器休息 API。我已经成功关闭了未经身份验证的客户端的 API。现在,每当我从 Angular 客户端发出请求时,我都需要在 header 中自动注入(inject)一个 token 。
我尝试的是实现这样的 HttpInterceptor :
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
setHeaders: {
'Content-Type' : 'application/json; charset=utf-8',
'Accept' : 'application/json',
'Authorization': `${this.authService.userToken}`,
//#endregion
},
})
return next.handle(req);
}
当使用标准的 Angular HttpClient 发出请求时,这对我来说总是很好。但是现在,当我使用 aws-amplify 包中的 API 向我的 API.Gateway 发出请求时,这些请求无法像这样被拦截。这是我提出请求的方式:
import { API } from 'aws-amplify';
.
.
.
return API.get('apiName', '/users',{})
而这些没有使用 Angular HttpClient。编辑 :
同样在 app.module.ts 中:
providers : [{
provide : HTTP_INTERCEPTORS,
useClass: HttpRequestInterceptor, --> My interceptor class
multi : true,
}]
任何人都知道我如何拦截这些请求到我的 API 网关以注入(inject) token ?有一个不错的!
最佳答案
使用 Axios 用于拦截使用 aws-amplify 包发出的请求,因为 aws-amplify 包使用 Axios 发出请求。
Axios is a Javascript library used to make HTTP requests from node.js or XMLHttpRequests from the browser and it supports the Promise API that is native to JS ES6. It can be used to intercept HTTP requests and responses and enables client-side protection against XSRF. It also has the ability to cancel requests.
在这种情况下,为拦截器创建一个新服务。
在 axios-interceptor.service.ts ,
import { Injectable } from '@angular/core';
import axios from 'axios';
@Injectable({providedIn: 'root'})
export class AxiosInterceptorService {
intercept() {
axios.interceptors.request.use(request => {
request.headers['Content-Type'] = 'application/json; charset=utf-8';
request.headers.Accept = 'application/json';
request.headers.Authorization = `${userToken}`;
return request;
});
}
}
export function AxiosConfigFactory(axiosIntercept: AxiosInterceptorService): any {
return () => axiosIntercept.intercept();
}
在 app.module.ts ,import { APP_INITIALIZER, NgModule } from '@angular/core';
import { AxiosConfigFactory, AxiosInterceptorService } from './axios-interceptor-service.service';
providers: [
{
provide: APP_INITIALIZER,
useFactory: AxiosConfigFactory,
deps: [AxiosInterceptorService],
multi: true
}
],
此外,我们还可以通过在intercept() 方法中使用以下代码来处理错误响应。axios.interceptors.response.use(response => {
return Promise.resolve(response);
}, errorObject => {
return Promise.reject(errorObj.response);
});
PS:我真的很难弄清楚这一点。甚至认为答案很晚,我希望它可以帮助将来的人:)
关于angular - 由 aws API 制作的 HttpRequest 拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64488595/