request.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // 此vm参数为页面的实例,可以通过它引用vuex中的变量
  2. import {
  3. mainUrl
  4. } from './baseUrl';
  5. module.exports = (vm) => {
  6. // 初始化请求配置
  7. uni.$u.http.setConfig((config) => {
  8. /* config 为默认全局配置*/
  9. config.baseURL = mainUrl //'http://t28.9026.com'; /* 根域名 */ //本地测试环境
  10. //config.baseURL = 'http://gift.cn'; /* 根域名 */ //演示测试环境
  11. //config.baseURL = 'http://gift.cn'; /* 根域名 */ //生成环境
  12. return config
  13. })
  14. // 请求拦截
  15. uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
  16. let token=uni.getStorageSync("token")
  17. config.header = {
  18. // "User-Agent":"apifox/1.0.0 (https://www.apifox.cn)",
  19. "Content-Type": "application/json",
  20. // ...config.header,
  21. // Authorization: `Bearer ${vm.$store.state.token}`
  22. Authorization: token
  23. }
  24. return config
  25. }, config => { // 可使用async await 做异步操作
  26. return Promise.reject(config)
  27. })
  28. // 响应拦截
  29. uni.$u.http.interceptors.response.use((response) => {
  30. /* 对响应成功做点什么 可使用async await 做异步操作*/
  31. const data = response.data
  32. const header = response.header
  33. // if (header.token) {
  34. // vm.$store.commit('user/setToken', header.token)
  35. // }
  36. //
  37. // 自定义参数
  38. const custom = response.config?.custom
  39. if (data.code !== 200) {
  40. if (data.code == 400) {
  41. vm.$store.commit('setToken', null)
  42. return Promise.reject(data)
  43. }
  44. // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
  45. if (custom.toast !== false) {
  46. //uni.$u.toast(data.message)
  47. }
  48. return Promise.reject(data)
  49. // 如果需要catch返回,则进行reject
  50. if (custom?.catch) {
  51. return Promise.reject(data)
  52. } else {
  53. // 否则返回一个pending中的promise,请求不会进入catch中
  54. return new Promise(() => {})
  55. }
  56. }
  57. return data.data === undefined ? {} : data.data
  58. }, (response) => {
  59. // 对响应错误做点什么 (statusCode !== 200)
  60. return Promise.reject(response)
  61. })
  62. }