request.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import env from './env.js'
  2. import Vue from 'vue'
  3. import auth from './auth.js'
  4. function service(options = {}) {
  5. options.url = `${env.baseUrl}${options.url}`;
  6. //判断本地是否带有token,如果带有,则添加到请求中
  7. const token =uni.getStorageSync("token")
  8. if (token) {
  9. options.header = {
  10. "content-type": "application/json",
  11. "Authorization": "Bearer " + token
  12. }
  13. }
  14. return new Promise((resolve, reject) => {
  15. options.success = (res) => {
  16. //如果返回的状态码不是200,则执行以下操作
  17. if (res.statusCode !== 200) {
  18. uni.showToast({
  19. icon: 'none',
  20. duration: 3000,
  21. title: `${res.errMsg}`
  22. });
  23. //403错误需要重新登录
  24. if (res.statusCode === 403) {
  25. auth.removeToken()
  26. uni.reLaunch({
  27. url: "/pages/login/login.vue"
  28. })
  29. }
  30. //返回错误信息
  31. reject(res)
  32. } else {
  33. const code = res.data.code
  34. if (code === 1011006 || code === 1011007 || code === 1011008 || code === 1011009) {
  35. uni.showToast({
  36. icon: 'none',
  37. mask: true,
  38. duration: 3000,
  39. title: `${res.data.message},需要重新登录`,
  40. success() {
  41. auth.removeToken()
  42. uni.reLaunch({
  43. url: "/pages/login/login.vue"
  44. })
  45. }
  46. })
  47. } else if (code !== 200) {
  48. uni.showToast({
  49. icon: 'none',
  50. duration: 3000,
  51. title: `${res.data.message}`
  52. })
  53. }
  54. resolve(res)
  55. }
  56. };
  57. options.fail = (res) => {
  58. uni.showToast({
  59. icon: 'none',
  60. duration: 3000,
  61. title: '服务器错误,请稍后在试'
  62. })
  63. reject(res)
  64. }
  65. uni.request(options)
  66. })
  67. }
  68. export default service