有一个通过 NSwag.MSBuild 包自动生成的 API 代理获取客户端,它有这样的构造函数。我需要通过 init 参数传递授权标头。
export class CustomerClient implements ICustomerClient {
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
this.http = http ? http : <any>window;
this.baseUrl = baseUrl !== undefined && baseUrl !== null ? baseUrl : "";
}
...
...
...
}
有什么可能的方法可以通过吗?
也许这会对你有帮助
const apiClient = new CustomerClient(`http://localhost:5000`, {
async fetch(url: RequestInfo, init: RequestInit) {
const accessToken = await acquireAccessToken();
if (accessToken) init.headers['Authorization'] = `Bearer ${accessToken}`;
return fetch(url, init);
},
});