Service 请求服务
WARNING
service.xx
请求方式目前已下线,后续版本将以更优的方式重新提供。- 当前推荐使用
request
方法进行接口请求。
请求配置
ts
type RequestOptions = {
url: string; // 请求地址
method?: RequestMethod; // 请求方法 (GET, POST, PUT, DELETE等)
data?: any; // 请求体数据
params?: any; // URL查询参数
header?: any; // 自定义请求头
timeout?: number; // 超时时间(毫秒)
withCredentials?: boolean; // 是否携带凭证信息
firstIpv4?: boolean; // 是否优先使用IPv4
enableChunked?: boolean; // 是否启用分块传输编码
};
响应数据结构
ts
type Response = {
code?: number; // 响应状态码
message?: string; // 响应消息
data?: any; // 响应数据
};
使用指南
当需要更灵活的请求配置时,可以使用request
方法:
- 请求参数必须提供默认值
{}
request
必须带返回值类型
ts
import { request, type Response, type UserAddressEntity, parse } from "@/cool";
import { useUi } from "@/uni_modules/cool-ui";
import { ref } from "vue";
const ui = useUi();
// 返回值类型,根据实际场景去修改
type Pagination = {
total: number;
page: number;
size: number;
};
type PageResponse = {
list: UTSJSONObject[];
pagination: Pagination;
};
// 自定义请求配置
request({
url: "/app/user/address/page", // URL会自动拼接config中的baseUrl
method: "POST",
data: {
page: 1,
size: 10,
},
})
.then((res) => {
if (res != null) {
// 需要手动进行类型转换
const { list, pagination } = parse<PageResponse>(res)!;
}
})
.catch((err) => {
// 统一的错误处理
ui.showToast({
message: (err as Response).message!,
});
});
重要提示
类型安全
- 错误处理:
catch
回调中的err
参数必须使用as Response
进行类型断言,否则在 APP 端会报错 - 类型一致性:赋值变量的类型必须与返回数据类型一致,或通过适当的类型转换处理
- 泛型指定:使用
request
方法时,需要明确指定返回数据类型,未知类型可使用UTSJSONObject
请求参数
- 默认值:所有请求参数都必须提供默认值
{}
,这是由于 uni-app 框架限制 - URL 处理:请求 URL 会自动拼接配置文件中的
baseUrl
- 第三方接口:支持直接使用
http
或https
开头的完整 URL 调用第三方服务