创建文件夹:utils-request.js
1,使用uview中封装好的 (封装的是uniapp中的网络请求)
在requestjs文件夹中代码如下:
// 初始化请求配置
uni.$u.http.setConfig((config) => {
/* config 为默认全局配置*/
config.baseURL = ' '; /* 根域名 */
return config
})
// 请求拦截
uni.$u.http.interceptors.request.use((config) => {
// 可使用async await 做异步操作
// 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
config.data = config.data || {}
if (uni.getStorageSync('token')) {
config.header.Authorization = uni.getStorageSync('token')
}
return config
}, config => {
// 可使用async await 做异步操作
return Promise.reject(config)
})
// 响应拦截
uni.$u.http.interceptors.response.use((response) => {
/* 对响应成功做点什么 可使用async await 做异步操作*/
const data = response.data
// 自定义参数
const custom = response.config?.custom
if (data.code !== 200) {
// 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
if (custom.toast !== false) {
console.log(data)
uni.$u.toast(data.message)
if (data.code === 401) {
setTimeout(() => {
uni.reLaunch({
url: '/pages/login/index'
})
}, 300)
}
}
return Promise.reject(data)
}
return data.data
}, (response) => {
// 对响应错误做点什么 (statusCode !== 200)
return Promise.reject(response)
})
main.js导入
import '@/utils/request.js';
2.使用promise自己进行进行封装 (用的是uniapp中的网络请求)。
requestjs文件代码如下:
const baseUrl = '' /* 根域名 */
const request = (url = '', options = {}, contentType = 'application/json') => {
return new Promise((resolve, reject) => {
uni.showLoading({
title: '加载中',
mask: true
});
uni.request({
method: options.method,
url: baseUrl + url,
data: options.data,
header: {
'Content-Type': contentType,
'Authorization': uni.getStorageSync('token')
},
dataType: 'json',
}).then((response) => {
uni.hideLoading();
let [error, res] = response;
if (res.data.code === 200) {
resolve(res.data.data);
} else {
if (res.data.code === 401) {
uni.showToast({
title: res.data.message || '登录已过期',
icon: 'none',
complete() {
uni.removeStorageSync('userInfo');
uni.removeStorageSync('token');
uni.reLaunch({
url: '/pages/login/login'
})
}
});
} else {
uni.showToast({
title: res.data.message,
icon: 'none'
});
}
reject(res.data.message)
}
}).catch(error => {
reject(error)
})
});
}
const get = (url, data) => {
return request(url, {
method: 'GET',
data: data
})
}
const post = (url, data) => {
return request(url, {
method: 'POST',
data: data
})
}
const postQuery = (url, data) => {
return request(url, {
method: 'POST',
data: data
}, 'application/x-www-form-urlencoded')
}
const put = (url, data) => {
return request(url, {
method: 'PUT',
data: data
})
}
module.exports = {
get,
post,
postQuery,
put
}
在main.js中导入
import Api from 'utils/request.js'
Vue.prototype.$api = Api