| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- import {
- store
- } from '@/store/index.js'
- /**
- * 文档地址:https://uiadmin.net/uview-plus/js/http.html
- */
- const baseUrl = 'http://bk.shuhi.com'
- export function initRequest() {
- console.log('初始化了 http 请求代码')
- // 初始化请求配置
- uni.$u.http.setConfig((config) => {
- /* config 为默认全局配置*/
- // config.baseURL = `http://192.168.1.2:8080`; /* 根域名 */
- config.baseURL = baseUrl; /* 根域名 */
- config.custom.toast = true // 默认消息有msg会显示出来
- return config
- })
- // 请求拦截
- uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
- // console.log('请求拦截', config)
- // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
- config.data = config.data || {}
- // 挂载 token
- let token = store.token || uni.getStorageSync('token')
- config.header.Authorization = token ? `Bearer ${token}` : ''
- return config
- }, config => { // 可使用async await 做异步操作
- return Promise.reject(config)
- })
- // 响应拦截
- uni.$u.http.interceptors.response.use((response) => {
- /* 对响应成功做点什么 可使用async await 做异步操作*/
- // console.log('响应拦截', response)
- const data = response.data
- // 自定义参数
- const custom = response.config?.custom
- if (data.code !== 200) {
- // 身份认证失败,需要重新登录
- if (data.code === 401) {
- uni.$u.toast(data.msg || '身份认证失败,请先登录')
- uni.removeStorageSync('token')
- store.setToken('') // 清空token
- setTimeout(() => {
- uni.$u.route({
- type: 'reLaunch',
- url: '/pages/login/login' // 跳转到登录页
- })
- }, 1000)
- } else {
- // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
- if (custom.toast !== false) {
- uni.$u.toast(data.msg)
- }
- // 如果需要catch返回,则进行reject
- // if (custom?.catch) {
- // return Promise.reject(data)
- // } else {
- // // 否则返回一个pending中的promise,请求不会进入catch中
- // return new Promise(() => { })
- // }
- return data
- }
- }
- // return data.data === undefined ? {} : data.data
- return data // 这里视不同的后端返回数据格式而定
- }, (response) => {
- // 对响应错误做点什么 (statusCode !== 200)
- return Promise.reject(response)
- })
- }
- export default baseUrl
|