更新:登录功能
This commit is contained in:
45
api/request.ts
Normal file
45
api/request.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
// api/request.ts
|
||||
import { requestInterceptor } from './interceptors/request';
|
||||
import { responseInterceptor } from './interceptors/response';
|
||||
import type { IRequestOptions, ICreateClientConfig } from './types';
|
||||
import { REQUEST_TIMEOUT } from './config';
|
||||
|
||||
export function createRequestClient(cfg: ICreateClientConfig) {
|
||||
const baseURL = cfg.baseURL;
|
||||
const timeout = cfg.timeout ?? REQUEST_TIMEOUT;
|
||||
|
||||
async function request<T = any>(options: IRequestOptions): Promise<T> {
|
||||
// 组装 final options
|
||||
const final: UniApp.RequestOptions = {
|
||||
...options,
|
||||
url: (options.url || '').startsWith('http') ? options.url : `${baseURL}${options.url}`,
|
||||
timeout,
|
||||
header: options.header || {},
|
||||
};
|
||||
|
||||
// run request interceptor to mutate headers, etc.
|
||||
const intercepted = requestInterceptor(final as IRequestOptions);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
uni.request({
|
||||
...intercepted,
|
||||
success(res: any) {
|
||||
// delegate to response interceptor
|
||||
responseInterceptor(res)
|
||||
.then((r) => {
|
||||
resolve(r as any);
|
||||
})
|
||||
.catch((err) => {
|
||||
reject(err);
|
||||
});
|
||||
},
|
||||
fail(err: any) {
|
||||
uni.showToast({ title: '网络连接失败', icon: 'none' });
|
||||
reject(err);
|
||||
},
|
||||
} as any);
|
||||
});
|
||||
}
|
||||
|
||||
return { request };
|
||||
}
|
||||
Reference in New Issue
Block a user