直接上代码:
// 接口地址
import BASE_URL from './base_url.js'
const http = (options) => {
const seesionKey = 'SESSIONID'
// 开始请求 展示加载中loading
uni.showLoading({
title: "加载中...",
});
return new Promise((resolve, reject) => {
uni.request({
url: BASE_URL + options.url, // 配置请求地址
data: options.data || {}, // 请求参数
// 配置请求头参数-例如token
header: options.header || {
"Content-Type": 'application/x-www-form-urlencoded;charset=utf-8',
'Cookie': `${seesionKey}=${uni.getStorageSync(seesionKey)}`
},
method: options.method || 'GET', // 请求方式 注意:最好使用大写
success: (res) => {
resolve(res)
},
fail: (err) => {
reject(err)
console.log('请求失败', err)
},
complete: (finish) => {
//请求结束 关闭加载loading
uni.hideLoading();
}
})
})
}
export {
http
}
BASE_URL
可查看 uni-app 如何根据环境自动切换请求的地址