request.js 2.3 KB

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