1、在src目录上创建util目录然后创建request.ts文件
// https://x.dscmall.cn/api/goods/type_list?page=1&size=10&type=is_best
// 通用的url路径
let baseURl = "https://x.dscmall.cn/api"
// 需要拦截的api名称,如uni.addInterceptor('request',OBJECt),将拦截uni.request()
// 拦截器
const interceptorOptions = {
// invoke拦截前触发
invoke(options : UniApp.RequestOptions) {
options.url = baseURl + options.url
// timeout请求时间
options.timeout = 10000
// 添加请求头
options.header = {
...options.header
}
// 添加token,token登录成功之后存放到状态管理中
const token = 'this is token'
if (token) {
options.header['token'] = token
}
}
}
uni.addInterceptor('request', interceptorOptions)
// 封装请求,使用Promise形式,之后就可以使用async await
export const requestApi = (options : UniApp.RequestOptions) => {
return new Promise((resolve, reject) => {
uni.request({
...options,
success: (res) => {
if (res.statusCode == 200) {
resolve(res.data)
} else {
uni.showToast({
"title": "请求失败",
duration: 2000
})
reject(res)
}
},
fail: (err) => {
uni.showToast({
"title": "请求失败",
duration: 2000
})
reject(err)
}
})
})
}
// options={
// url:"",
// method:"",
// data:{},
// header:{}
// }
// 等价于
// {
// ...options
// }
2、在src目录下创建api目录用于请求接口,下面创建home.ts文件
// 引入封装的请求数据模块
import { requestApi } from "../utils/request"
// 导出请求数据的方法
// 接口地址https://x.dscmall.cn/api/goods/type_list
// 请求的方式get
// 参数page=1&size=10&type=is_best
// 定于参数接口
// interface IHomeList {
// page : number | string,
// size : number | string,
// type : string
// }
// 定义参数类型
type THomeList = {
page : number | string,
size : number | string,
type : string
}
export const HomeListApi = (data : THomeList) => {
return requestApi({
url: "/goods/type_list",
method: "GET",
data
})
}
3、在所需请求数据的页面调用接口
4、渲染数据