学员端小程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.9 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. import { H5_API, WX_API } from './site.config.js'
  2. // 此vm参数为页面的实例,可以通过它引用vuex中的变量
  3. module.exports = (vm) => {
  4. // 初始化请求配置
  5. uni.$u.http.setConfig((config) => {
  6. let prefix = config.prefix?config.prefix:'app-api/'
  7. /* config 为默认全局配置*/
  8. config.baseURL = H5_API+ WX_API + prefix; /* 根域名 */
  9. console.log(config.baseURL)
  10. // config.header['content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
  11. config.header['tenant-id'] = '1'
  12. return config
  13. })
  14. // 请求拦截
  15. uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
  16. // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
  17. config.data = config.data || {}
  18. // 根据custom参数中配置的是否需要token,添加对应的请求头
  19. // config.header.Authorization = 'Bearer ' + vm.$store.state.user.vuex_loginInfo.accessToken
  20. return config
  21. }, config => { // 可使用async await 做异步操作
  22. return Promise.reject(config)
  23. })
  24. // 响应拦截
  25. uni.$u.http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
  26. const data = response.data
  27. console.log('请求结果')
  28. console.log(data)
  29. // 自定义参数
  30. const custom = response.config?.custom
  31. if (data.code !== 0) {
  32. // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
  33. if (custom.toast !== false) {
  34. uni.$u.toast(data.msg)
  35. }
  36. // 如果需要catch返回,则进行reject
  37. if (custom?.catch) {
  38. return Promise.reject(data)
  39. } else {
  40. // 否则返回一个pending中的promise,请求不会进入catch中
  41. return new Promise(() => { })
  42. }
  43. }
  44. return data === undefined ? {} : data
  45. }, (response) => {
  46. // 对响应错误做点什么 (statusCode !== 200)
  47. return Promise.reject(response)
  48. })
  49. }