upload.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. // 配置项
  2. import Notify from '../miniprogram_npm/@vant/weapp/notify/notify';
  3. import { $startWuxRefresher, $stopWuxRefresher,$stopWuxLoader} from '../miniprogram_npm/wux-weapp/index';
  4. const token = wx.getStorageSync('token')
  5. const config = {
  6. baseURL: 'http://192.168.1.6:8802', // 基础URL
  7. // baseURL: 'https://www.xsip.cn', // 基础URL
  8. timeout: 30000, // 超时时间(单位ms)
  9. header: {
  10. 'content-type': 'application/json', // 默认请求头
  11. // 其他全局请求头...
  12. },
  13. // 其他全局配置...
  14. tabbar:["pages/index/index","pages/hotProduct/hotProduct","pages/mine/mine"]
  15. };
  16. // 封装请求方法
  17. function upload(url="/fileManager/uploadNormalFile", path = '', header = {},formData={}) {
  18. return new Promise((resolve, reject) => {
  19. var obj = {
  20. type: 'danger'
  21. }
  22. var pages = getCurrentPages()
  23. var route = pages[pages.length - 1]?.route
  24. console.log(config.tabbar,route)
  25. if(route && config.tabbar.indexOf(route)==-1){
  26. obj.top = "90"
  27. }
  28. wx.uploadFile({
  29. url: config.baseURL + url, //仅为示例,非真实的接口地址
  30. filePath: path,
  31. name: 'files',
  32. formData: {
  33. sourceId:5,
  34. ...formData
  35. },
  36. header: {
  37. ...config.header,
  38. ...header,
  39. "Cookie": "token="+wx.getStorageSync('token')
  40. },
  41. timeout: config.timeout,
  42. success: function(res){
  43. if(res.data){
  44. res.data = JSON.parse(res.data)
  45. }
  46. // 根据业务逻辑处理成功响应
  47. if (res.data && res.data.code === 200) { // 假设服务器返回code为200表示成功
  48. resolve(res.data);
  49. } else {
  50. switch(res.data.code){
  51. case 401:
  52. if(isLogin){
  53. // Notify({ type: 'danger', message: '未登录',top:'90' });
  54. obj.message = '未登录'
  55. wx.navigateTo({
  56. url: '/pages/login/login',
  57. })
  58. }
  59. wx.setStorageSync('token', '')
  60. break;
  61. default:
  62. obj.message = '请求失败'
  63. // Notify({ type: 'danger', message: '请求失败',top:'90' });
  64. }
  65. // wx.showToast({
  66. // title: '请求失败',
  67. // icon: 'error',
  68. // duration: 2000
  69. // })
  70. console.log(obj)
  71. if(obj.message){
  72. Notify(obj)
  73. }
  74. reject(res.data.message || '未知错误');
  75. }
  76. if($stopWuxRefresher()){
  77. $stopWuxRefresher()
  78. }
  79. },
  80. fail: function(error) {
  81. console.log(error)
  82. // 处理请求失败
  83. // wx.showToast({
  84. // title: '请求失败',
  85. // icon: 'error',
  86. // duration: 2000
  87. // })
  88. obj.message = '请求失败'
  89. // Notify({ type: 'danger', message: '请求失败',top:'90' });
  90. Notify(obj)
  91. reject(error);
  92. },
  93. });
  94. });
  95. }
  96. // 导出请求方法
  97. module.exports = {
  98. upload: ( path,formData,url, header) => upload(url, path, header,formData),
  99. };