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.

71 lines
2.1 KiB

  1. import { useUserStore } from "../stores/modules/userInfo";
  2. const baseURL = "http://localhost:8888"
  3. const httpInterceptor = {
  4. // 拦截前触发
  5. invoke(options) {
  6. // 1.非http
  7. if (!options.url.startsWith('http')) {
  8. options.url = baseURL + options.url
  9. }
  10. // 2.请求超时,默认60s
  11. options.timeout = 60000
  12. console.log(options)
  13. //3 添加小程序端请求头
  14. options.header = {
  15. ...options.header,
  16. 'source-client': 'miniapp'
  17. }
  18. //4 添加token
  19. const memberStore = useUserStore()
  20. const token = memberStore.userInfo?.token
  21. if (token) {
  22. options.header.Authorization = {
  23. 'token': token
  24. }
  25. }
  26. return options
  27. }
  28. }
  29. // 添加拦截器
  30. uni.addInterceptor('request', httpInterceptor)
  31. uni.addInterceptor('uploadFile', httpInterceptor)
  32. // 添加请求函数
  33. export const http = (options) => {
  34. return new Promise((resolve, reject) => {
  35. uni.request({
  36. ...options,
  37. // 1.请求成功
  38. success: (result) => {
  39. if (result.statusCode >= 200 && result.statusCode < 300) {
  40. resolve(result.data)
  41. } else if (result.statusCode === 401) {
  42. // 清除登录信息
  43. const memberStore = useUserStore()
  44. memberStore.clearUserInfo()
  45. // 提示用户重新登录
  46. uni.navigateTo({
  47. url: '/pages/login/login'
  48. })
  49. reject(result)
  50. } else {
  51. uni.showToast({
  52. title: (result.data).msg || '请求失败',
  53. icon: 'none'
  54. })
  55. reject(result)
  56. }
  57. },
  58. // 2.请求失败
  59. fail: (err) => {
  60. reject(err)
  61. uni.showToast({
  62. title: '网络错误',
  63. icon: 'none'
  64. })
  65. }
  66. })
  67. })
  68. }