69 lines
1.7 KiB
JavaScript
69 lines
1.7 KiB
JavaScript
const baseUrl = process.env.REQUEST_BASE_URL
|
||
|
||
function request(options) {
|
||
uni.showLoading({
|
||
title: "加载中",
|
||
mask: true,
|
||
});
|
||
let defaultHeader = {
|
||
|
||
}
|
||
// // 如果使用params传参则,以&符拼接的格式传参
|
||
if (options.params) {
|
||
options.data = options.params
|
||
defaultHeader['Content-Type'] = 'application/json'
|
||
// defaultHeader['Content-Type'] = 'application/x-www-form-urlencoded'
|
||
}
|
||
const token = uni.getStorageSync('token');
|
||
if (token) {
|
||
defaultHeader.Authorization = `Bearer ${token}`
|
||
}
|
||
return new Promise((resolve, reject) => {
|
||
uni.request({
|
||
url: baseUrl + options.url, // 接口地址:前缀+方法中传入的地址
|
||
method: options.method || 'GET', // 请求方法:传入的方法或者默认是“GET”
|
||
data: options.data || {}, // 传递参数:传入的参数或者默认传递空集合
|
||
header: {
|
||
...defaultHeader,
|
||
...options.header
|
||
},
|
||
success: (res) => {
|
||
if (res.statusCode && res.statusCode != 200) {
|
||
uni.hideLoading().then(() => {
|
||
uni.showToast({
|
||
title: "api错误" + res.errMsg,
|
||
icon: 'none'
|
||
});
|
||
})
|
||
reject()
|
||
} else {
|
||
const resData = res.data
|
||
if (resData.code == 200) {
|
||
uni.hideLoading()
|
||
resolve(resData.data)
|
||
} else {
|
||
uni.hideLoading().then(() => {
|
||
uni.showToast({
|
||
title: '请求失败了,稍后再试',
|
||
icon: 'none'
|
||
});
|
||
})
|
||
reject(res.msg)
|
||
}
|
||
}
|
||
},
|
||
// 这里的接口请求,如果出现问题就输出接口请求失败
|
||
fail: (err) => {
|
||
uni.hideLoading().then(() => {
|
||
uni.showToast({
|
||
title: err,
|
||
icon: 'none'
|
||
});
|
||
})
|
||
reject(err)
|
||
}
|
||
})
|
||
})
|
||
}
|
||
|
||
export default request |