1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- // 此vm参数为页面的实例,可以通过它引用vuex中的变量
- import {
- mainUrl
- } from './baseUrl';
- module.exports = (vm) => {
- // 初始化请求配置
- uni.$u.http.setConfig((config) => {
- /* config 为默认全局配置*/
- config.baseURL = mainUrl //'http://t28.9026.com'; /* 根域名 */ //本地测试环境
- //config.baseURL = 'http://gift.cn'; /* 根域名 */ //演示测试环境
- //config.baseURL = 'http://gift.cn'; /* 根域名 */ //生成环境
- return config
- })
- // 请求拦截
- uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
- let token=uni.getStorageSync("token")
- config.header = {
- // "User-Agent":"apifox/1.0.0 (https://www.apifox.cn)",
- "Content-Type": "application/json",
- // ...config.header,
- // Authorization: `Bearer ${vm.$store.state.token}`
- Authorization: token
- }
- return config
- }, config => { // 可使用async await 做异步操作
- return Promise.reject(config)
- })
- // 响应拦截
- uni.$u.http.interceptors.response.use((response) => {
- /* 对响应成功做点什么 可使用async await 做异步操作*/
- const data = response.data
- const header = response.header
- // if (header.token) {
- // vm.$store.commit('user/setToken', header.token)
- // }
- //
- // 自定义参数
- const custom = response.config?.custom
- if (data.code !== 200) {
- if (data.code == 400) {
- vm.$store.commit('setToken', null)
- return Promise.reject(data)
- }
- // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
- if (custom.toast !== false) {
- //uni.$u.toast(data.message)
- }
- return Promise.reject(data)
- // 如果需要catch返回,则进行reject
- if (custom?.catch) {
- return Promise.reject(data)
- } else {
- // 否则返回一个pending中的promise,请求不会进入catch中
- return new Promise(() => {})
- }
- }
- return data.data === undefined ? {} : data.data
- }, (response) => {
- // 对响应错误做点什么 (statusCode !== 200)
- return Promise.reject(response)
- })
- }
|