对uni.request的一些共同参数进行简单的封装,减少重复性数据请求代码。方便全局调用。
先在目录下创建 utils 目录,紧接着在 utils 目录下面创建一个 api.js 文件
接下来我们就在刚创建的文件中做一个简单地uni.request 的请求封装。
废话不多说,直接上代码!
api.js文件
export const baseUrl = 'https://api.bingxizg.com/api'
function mylogin() {
return new Promise((resolve, reject) => {
wx.login({
success: (res) => {
if (res.code) {
wx.request({
url: baseUrl + '/wxLogin',
method: 'POST',
data: {
code: res.code
},
success: (res) => {
console.log(res);
if (res.data.code == 200) {
uni.setStorageSync('token', res.data.data.token)
resolve(true)
}
}
})
} else {
console.log('登录失败!' + res.errMsg)
}
}
})
})
}
// 获取请求头 判断token是否存在
async function getHeaders() {
if (!uni.getStorageSync('token')) {
await mylogin()
}
let header = {
Accept: 'application/json',
"Content-Type": "application/json", //根据自己的数据类型
Authorization: 'Bearer ' + uni.getStorageSync('token')
}
return header
}
//访客登录
export const requestApi = function(data) {
data.method = data.method ? data.method.toUpperCase() : 'GET'
if (!['GET', 'POST'].includes(data.method)) {
uni.showToast({
title: `暂不支持的请求方式: ${data.method}`,
icon: 'none'
});
return
}
return new Promise(async (resolve, reject) => {
uni.request({
url: baseUrl + data.url,
method: data.method,
data: data.params,
header: await getHeaders(),
success: (res) => {
resolve(res)
},
error: (err) => {
reject(err)
}
})
}).then(res => {
return res
}).catch(
(response) => {
uni.showToast({
title: `请求错误: ${response.data.message}`,
icon: 'none'
});
}
)
}
在main.js文件中引入
import { requestApi } from '/until/api.js'
App.config.globalProperties.$request = requestApi
index文件中使用
this.$request({
url: '/userInfo',
params:{},
method:'GET'
}).then((res) => {
console.log(res)
})