如何将授权标头传递给 NSwag 生成的获取客户端?

问题描述 投票:0回答:1

有一个通过 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 : "";
    }
...
...
...
}

有什么可能的方法可以通过吗?

reactjs typescript fetch-api nswag
1个回答
0
投票

也许这会对你有帮助

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);
    },
});
© www.soinside.com 2019 - 2024. All rights reserved.