request.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import {
  2. getToken,
  3. setToken
  4. } from './auth.js'
  5. import {
  6. toast
  7. } from './common.js'
  8. import config from '../config.js'
  9. // const BASE_URL = config.service
  10. const BASE_URL = ''
  11. const request = config => {
  12. config.header = config.header || {
  13. 'content-type': 'application/json',
  14. 'cache-control': 'no-cache',
  15. 'Access-Control-Allow-Headers': 'appId',
  16. 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',
  17. 'Access-Control-Max-Age': 86400,
  18. }
  19. let isRequest = true
  20. if (getToken()) {
  21. config.header['Authorization'] = 'Bearer ' + getToken()
  22. }
  23. uni.hideKeyboard()
  24. console.log("入参:", config, BASE_URL + config.url)
  25. if (isRequest) {
  26. return new Promise((resolve, reject) => {
  27. uni.request({
  28. header: config.header,
  29. method: config.method.toUpperCase() || 'GET',
  30. dataType: 'json',
  31. timeout: config.timeout || 30000,
  32. url: BASE_URL + config.url,
  33. data: config.data,
  34. }).then((res) => {
  35. console.log("请求返回:", res)
  36. if (res.statusCode === 200) {
  37. const {
  38. code,
  39. msg
  40. } = res.data
  41. if (code === 401) {
  42. uni.hideLoading()
  43. uni.showModal({
  44. title: '系统提示',
  45. content: '登录状态已过期,请重新登录',
  46. showCancel: false,
  47. success: function(res) {
  48. if (res.confirm) {
  49. uni.reLaunch({
  50. url: '/pages/login/index'
  51. })
  52. }
  53. }
  54. });
  55. } else if (code !== 200) {
  56. toast(msg)
  57. reject(code)
  58. }
  59. resolve(res.data)
  60. } else {
  61. toast('未知错误,请反馈给管理员')
  62. }
  63. }).catch(error => {
  64. console.log("error", error)
  65. let {
  66. message
  67. } = error
  68. if (message === 'Network Error') {
  69. message = '后端接口连接异常'
  70. } else if (message.includes('timeout')) {
  71. message = '系统接口请求超时'
  72. } else if (message.includes('Request failed with status code')) {
  73. message = '系统接口' + message.substr(message.length - 3) + '异常'
  74. }
  75. toast(message)
  76. reject(error)
  77. })
  78. })
  79. }
  80. }
  81. export default request