我正在使用 Angular 10。我正在使用 openapi codegen(自动生成)服务。
问题:我想在我的 header 中传递 Authorization: Token 123456
但似乎无法理解如何以及在何处添加拦截器。
我的组件文件是:
constructor(
private meApi : MeService
)
meDetails;
meCheck(){
this.meApi.meRead().subscribe(
(data: any) => {
this.meDetails= data;
},
(err) => { console.error(err); },
() => { }
)
}
在 ngOnInIt 中运行这个函数。我收到以下错误:
401 (Unauthorized)
因为很明显,授权 token 没有通过 API 传递。
自动生成的服务文件中的meRead()函数有如下相关代码:
/**
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public meRead(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<User>;
public meRead(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpResponse<User>>;
public meRead(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json'}): Observable<HttpEvent<User>>;
public meRead(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json'}): Observable<any> {
let headers = this.defaultHeaders;
// authentication (DRF Token) required
if (this.configuration.apiKeys) {
const key: string | undefined = this.configuration.apiKeys["DRF Token"] || this.configuration.apiKeys["Authorization"];
if (key) {
headers = headers.set('Authorization', key);
}
}
let httpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (httpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
'application/json'
];
httpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
if (httpHeaderAcceptSelected !== undefined) {
headers = headers.set('Accept', httpHeaderAcceptSelected);
}
如何在此请求的 header 中传递授权: token 12345?
总结:如何在openapi codegen服务文件中传递Authorization header?
如能详细解答,将不胜感激。谢谢。
最佳答案
您可以通过更改生成的客户端的 defaultHeaders 属性来传递 header ,或者也可以通过在 ad-hoc 属性中提供一些配置来传递 header 。 看这个blog post对于其他一些选项。
/**
* OpenAPI definition [...]
*/
import { ...}
@Injectable({
providedIn: 'root'
})
export class UserControllerService {
protected basePath = 'http://localhost:8081';
public defaultHeaders = new HttpHeaders(); // <- here
public configuration = new Configuration(); // <- or there
public encoder: HttpParameterCodec;
{...}
}
至于通过方法调用的{httpHeaders: '/'}传递一些有用的东西,没看懂怎么办。
关于Angular - OpenApi CodeGen - 如何在 api 请求中添加 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65409263/