帮我使用ts封装uni.request
时间: 2023-11-11 15:03:34 浏览: 141
以下是使用 TypeScript 封装 uni.request 的示例代码:
```typescript
interface RequestOptions {
url: string;
method?: string;
data?: any;
header?: any;
dataType?: string;
responseType?: string;
success?: (res: any) => void;
fail?: (err: any) => void;
complete?: () => void;
}
function request(options: RequestOptions) {
uni.request({
url: options.url,
method: options.method || 'GET',
data: options.data || {},
header: options.header || {},
dataType: options.dataType || 'json',
responseType: options.responseType || 'text',
success: options.success || ((res) => {}),
fail: options.fail || ((err) => {}),
complete: options.complete || (() => {}),
});
}
```
使用方式:
```typescript
request({
url: 'https://example.com/api',
method: 'POST',
data: {
name: 'John',
age: 30,
},
header: {
'Content-Type': 'application/json',
},
success: (res) => {
console.log(res.data);
},
fail: (err) => {
console.error(err);
},
});
```
阅读全文