request.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import {
  2. store
  3. } from '@/store/index.js'
  4. /**
  5. * 文档地址:https://uiadmin.net/uview-plus/js/http.html
  6. */
  7. const baseUrl = 'http://bk.shuhi.com'
  8. export function initRequest() {
  9. console.log('初始化了 http 请求代码')
  10. // 初始化请求配置
  11. uni.$u.http.setConfig((config) => {
  12. /* config 为默认全局配置*/
  13. // config.baseURL = `http://192.168.1.2:8080`; /* 根域名 */
  14. config.baseURL = baseUrl; /* 根域名 */
  15. config.custom.toast = true // 默认消息有msg会显示出来
  16. return config
  17. })
  18. // 请求拦截
  19. uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
  20. // console.log('请求拦截', config)
  21. // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
  22. config.data = config.data || {}
  23. // 挂载 token
  24. let token = store.token || uni.getStorageSync('token')
  25. config.header.Authorization = token ? `Bearer ${token}` : ''
  26. return config
  27. }, config => { // 可使用async await 做异步操作
  28. return Promise.reject(config)
  29. })
  30. // 响应拦截
  31. uni.$u.http.interceptors.response.use((response) => {
  32. /* 对响应成功做点什么 可使用async await 做异步操作*/
  33. // console.log('响应拦截', response)
  34. const data = response.data
  35. // 自定义参数
  36. const custom = response.config?.custom
  37. if (data.code !== 200) {
  38. // 身份认证失败,需要重新登录
  39. if (data.code === 401) {
  40. uni.$u.toast(data.msg || '身份认证失败,请先登录')
  41. uni.removeStorageSync('token')
  42. store.setToken('') // 清空token
  43. setTimeout(() => {
  44. uni.$u.route({
  45. type: 'reLaunch',
  46. url: '/pages/login/login' // 跳转到登录页
  47. })
  48. }, 1000)
  49. } else {
  50. // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
  51. if (custom.toast !== false) {
  52. uni.$u.toast(data.msg)
  53. }
  54. // 如果需要catch返回,则进行reject
  55. // if (custom?.catch) {
  56. // return Promise.reject(data)
  57. // } else {
  58. // // 否则返回一个pending中的promise,请求不会进入catch中
  59. // return new Promise(() => { })
  60. // }
  61. return data
  62. }
  63. }
  64. // return data.data === undefined ? {} : data.data
  65. return data // 这里视不同的后端返回数据格式而定
  66. }, (response) => {
  67. // 对响应错误做点什么 (statusCode !== 200)
  68. return Promise.reject(response)
  69. })
  70. }
  71. export default baseUrl