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.

85 lines
2.2 KiB

6 months ago
  1. import $config from '../config'
  2. import $util from './util'
  3. export default function http(url, param = {}, extraConfig) {
  4. //默认配置
  5. let defaultConfig = {
  6. token: true, //携带令牌
  7. loading: true, //显示加载
  8. mock: false, //模拟数据
  9. }
  10. //请求配置
  11. let httpConfig = { ...defaultConfig, ...extraConfig }
  12. httpConfig.mock ? httpConfig.config = $config.mock : httpConfig.config = $config[process.env.NODE_ENV]
  13. //携带令牌
  14. let token = uni.getStorageSync('token')
  15. if (token) {
  16. param.token = token
  17. } else if (httpConfig.token) {
  18. uni.showModal({
  19. title: '提示',
  20. content: '登录后才能操作哦~',
  21. showCancel: true,
  22. confirmText: '去登录',
  23. success: (e) => {
  24. if (e.confirm) this.$util.toast('点击登录')
  25. }
  26. })
  27. return Promise.reject('未登录')
  28. }
  29. //显示加载
  30. httpConfig.loading && $util.loading('努力加载中')
  31. //进行请求
  32. let baseUrl = httpConfig.config.baseUrl
  33. let header = {
  34. 'Content-Type': 'application/x-www-form-urlencoded',
  35. 'Cookie': uni.getStorageSync('cookie') ? `foxphp_ok=${uni.getStorageSync('cookie')}` : '',
  36. }
  37. return new Promise((resolve, reject) => {
  38. uni.request({
  39. url: `${baseUrl}/${url}`,
  40. data: param,
  41. header: header,
  42. method: 'POST',
  43. // method: Object.keys(param).length ? 'POST' : 'GET',
  44. success: (res) => {
  45. uni.setStorageSync('cookie', res.data.foxphp_ok)
  46. httpConfig.loading && uni.hideLoading()
  47. switch (res.statusCode) {
  48. case 200:
  49. if (res.data.code == 1) {
  50. //正常请求
  51. resolve(res.data)
  52. } else {
  53. //其他状况
  54. if(!res.data.msg=='notask'){
  55. res.data.msg && $util.toast(res.data.msg)
  56. }
  57. resolve(res.data)
  58. }
  59. break
  60. case 403:
  61. $util.toast('服务器拒绝')
  62. reject(JSON.stringify(res))
  63. break
  64. case 404:
  65. $util.toast('资源不存在')
  66. reject(JSON.stringify(res))
  67. break
  68. case 500:
  69. $util.toast('服务器异常')
  70. reject(JSON.stringify(res))
  71. break
  72. default:
  73. $util.toast('未知错误码')
  74. reject(JSON.stringify(res))
  75. }
  76. },
  77. fail: (err) => {
  78. httpConfig.loading && uni.hideLoading()
  79. $util.toast('网络异常')
  80. reject(JSON.stringify(err))
  81. }
  82. })
  83. })
  84. }