app_ancientSayings/utils/request/index - 副本.js
2023-09-19 19:31:19 +08:00

75 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 引入配置
import config from '@/config/index';
import {
myGetStorage
} from '@/utils/storage/index.js'
const requestInterceptors = (vm) => {
/**
* 请求拦截
* @param {Object} http
*/
uni.$u.http.interceptors.request.use((config) => {
// 可使用async await 做异步操作
// 初始化请求拦截器时会执行此方法此时data为undefined赋予默认{}
config.data = config.data || {};
const token = myGetStorage('token');
// config?.custom?.token &&
if (token) {
config.header.token = token;
}
// 可以在此通过vm引用vuex中的变量具体值在vm.$store.state中
// console.log(vm.$store.state);
return config
}, (config) => {
// 可使用async await 做异步操作
return Promise.reject(config)
})
}
const responseInterceptors = (vm) => {
/**
* 响应拦截
* @param {Object} http
*/
uni.$u.http.interceptors.response.use((response) => {
/* 对响应成功做点什么 可使用async await 做异步操作*/
const data = response.data
console.log(response, "============")
// 自定义参数
const custom = response.config?.custom
// // 服务端返回的状态码不等于200则reject()
if (data.status !== 1) {
// 如果没有显式定义custom的toast参数为false的话默认对报错进行toast弹出提示
if (custom.toast !== false) {
uni.$u.toast(data.message)
}
// 如果需要catch返回则进行reject
if (custom?.catch) {
return new Promise(() => {})
} else {
// 否则返回一个pending中的promise
return Promise.reject(data)
}
}
return data || {}
}, (response) => {
/* 对响应错误做点什么 statusCode !== 200*/
return Promise.reject(response)
})
}
// 初始化请求配置
const initRequest = (vm) => {
uni.$u.http.setConfig((defaultConfig) => {
/* defaultConfig 为默认全局配置 */
defaultConfig.baseURL = config.baseUrl;
/* 根域名 */
defaultConfig.header = config.header;
return defaultConfig
})
requestInterceptors()
responseInterceptors()
}
export {
initRequest
}