gpt4 book ai didi

reactjs - 如何在 NSwag Studio 生成的服务中注入(inject) JWT in react wih typescript

转载 作者:行者123 更新时间:2023-12-05 05:09:01 25 4
gpt4 key购买 nike

我正在使用 NSwag Studio 在使用 typescript 的 react 中生成服务类。以下是生成代码的示例:

export class BookingClient {
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 ? baseUrl : "";
}

getMarinaData(model: MarinaDataRequest): Promise<MarinaDataResponse> {
let url_ = this.baseUrl + "/api/booking/marina/data";
url_ = url_.replace(/[?&]$/, "");

const content_ = JSON.stringify(model);

let options_ = <RequestInit>{
body: content_,
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
};

return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processGetMarinaData(_response);
});
}

protected processGetMarinaData(response: Response): Promise<MarinaDataResponse> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
result200 = _responseText === "" ? null : <MarinaDataResponse>JSON.parse(_responseText, this.jsonParseReviver);
return result200;
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<MarinaDataResponse>(<any>null);
}
}

我的问题是,如何为 protected 端点添加或注入(inject) JWT。假设并非所有端点都受到保护。感谢您的帮助。

最佳答案

创建基类并覆盖 transformOptions 方法。

export class BaseClass {

protected transformOptions = async (options: RequestInit): Promise<RequestInit> => {
let token = getToken(); // your custom logic to get the token

options.headers = {
...options.headers,
Authorization: 'Bearer ' + token,
};
return Promise.resolve(options);
};
}

在你的 nswag.json 集合中:

"clientBaseClass": "BaseClass",
"extensionCode": "path/to/your/BaseClass.ts",
"useTransformOptionsMethod": true,

这会将它添加到所有端点,但我认为将 token 发送到不 protected 端点并没有什么坏处(它将被忽略)。

关于reactjs - 如何在 NSwag Studio 生成的服务中注入(inject) JWT in react wih typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57845469/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com