之前只使用@escook/request-miniprogram配置过微信小程序网络请求
近期在写钉钉小程序发现这个插件并不能适配钉钉小程序,通过查找找到了另外一个插件可以适配luch-request
使用npm下载
npm install luch-request -S
在main.js中引入并配置请求基地址、请求拦截器、响应拦截器等
import Request from 'luch-request' // 使用npm
const http = new Request();
uni.$http = http;
const baseUrl = '请求基地址'
// 设置全局配置
http.setConfig((config) => {
config.baseURL = baseUrl;
// 请求头其他配置
// 如: config.header.Authorization = '';
return config
})
// 请求拦截器
http.interceptors.request.use((config) => {
config.header['Content-type'] = 'application/json'
config.header = {
...config.header
}
// 权限认证
// config.header.Authorization =
return config
})
// 响应拦截器
http.interceptors.response.use(async (res) => {
console.log('请求拦截器', res);
/* 请求以后拦截器 */
if (res.statusCode != 200) {
return Promise.reject(res)
}
return res.data
}, (error) => { // 请求错误
console.log(error)
if (error.statusCode == 401) {
// 登录态失效则清除token:没有携带token、token没法再刷新
let msg = error.data.message || error.data
if (msg == null || msg == undefined) msg = '当前登录状态过期,请重新登录'
uni.clearStorageSync()
uni.showToast({
title: msg,
icon: 'none',
success() {
setTimeout(() => {
// 跳转到登录页
uni.navigateTo({
url: "/pages/login/login"
})
}, 1000)
}
})
} else {
let msg = error.data.message || error.data
uni.showToast({
title: msg,
icon: 'none',
duration: 2000
})
}
return Promise.reject(error)
})