第一步 创建 config.js
// 此vm参数为页面的实例,可以通过它引用vuex中的变量
import {
baseURL
} from ‘./api.js’;
module.exports = (vm) => {
// 初始化请求配置
uni.$u.http.setConfig((config) => {
/* config 为默认全局配置*/
config.baseURL = baseURL; /* 根域名 */
return config
})
// 请求拦截
uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
uni.showLoading({
title: ‘玩命加载中….’,
mask: true
});
const token = uni.getStorageSync(‘storage_key’);
// 登录接口 获取验证码 接口不需要token
if (config.url.indexOf(‘/getNoticeByTime’) != -1) {
} else {
config.header.Authorization = token.token;
}
return config;
}, config => { // 可使用async await 做异步操作
uni.showLoading({
title: ‘玩命加载中….’,
mask: true
});
return Promise.reject(config)
})
// 响应拦截
uni.$u.http.interceptors.response.use((response) => {
// 关闭加载中
uni.hideLoading()
/* 对响应成功做点什么 可使用async await 做异步操作*/
const data = response.data
// 自定义参数
const custom = response.config?.custom
if (data.code !== 200) {
// 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
if (data.code == 401) {
// vm.$u.toast(“操作异常”);
vm.$u.toast(data.msg);
// 清楚缓存
uni.clearStorageSync();
// 返回初始页
setTimeout(function(){uni.reLaunch({
url: ‘/pages/index/index’
})},3000);
} else {
vm.$u.toast(data.msg);
}
return Promise.reject(data.msg)
// // 如果需要catch返回,则进行reject
// if (custom?.catch) {
// return Promise.reject(data)
// } else {
// // 否则返回一个pending中的promise,请求不会进入catch中
// return new Promise(() => {})
// }
}
return data.data || data.rows ? (data.data ? data.data : data.rows) : {}
}, (response) => {
vm.$u.toast(“网络丢失”);
// 关闭加载中
uni.hideLoading()
return Promise.reject(response)
})
}
第二步 api.js文件
const http = uni.$u.http
const baseURL = ‘ ‘ //线上地址
const getNoticeByTime= (params, config = {}) => http.post(‘/register’, params, config)
export {
register
}
第三步 页面调用
import {
getNoticeByTime,
} from ‘../../config/api.js’;
getNoticeByTime({}).then((res) => {
this.noticeContent = res.noticeContent
}).catch(() => {
})