request.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // request.js
  2. import Notify from '../miniprogram_npm/@vant/weapp/notify/notify';
  3. // 配置项
  4. const token = wx.getStorageSync('token')
  5. const config = {
  6. baseURL: 'http://192.168.1.16:8901', // 基础URL
  7. timeout: 30000, // 超时时间(单位ms)
  8. header: {
  9. 'content-type': 'application/json', // 默认请求头
  10. "token":token
  11. // 其他全局请求头...
  12. },
  13. // 其他全局配置...
  14. };
  15. // 封装请求方法
  16. function request(url, method = 'GET', data = {}, header = {}) {
  17. return new Promise((resolve, reject) => {
  18. wx.request({
  19. url: config.baseURL + url,
  20. method: method.toUpperCase(),
  21. data: method === 'GET' ? {} : data, // GET请求时将data置为空对象
  22. header: {
  23. ...config.header,
  24. ...header,
  25. },
  26. timeout: config.timeout,
  27. success: function(res){
  28. // 根据业务逻辑处理成功响应
  29. if (res.data && res.data.code === 200) { // 假设服务器返回code为200表示成功
  30. resolve(res.data);
  31. } else {
  32. switch(res.data.code){
  33. case 401:
  34. Notify({ type: 'danger', message: '未登录' });
  35. wx.navigateTo({
  36. url: '/pages/login/login',
  37. })
  38. break;
  39. default:
  40. Notify({ type: 'danger', message: '请求失败' });
  41. }
  42. // wx.showToast({
  43. // title: '请求失败',
  44. // icon: 'error',
  45. // duration: 2000
  46. // })
  47. reject(res.data.message || '未知错误');
  48. }
  49. },
  50. fail: function(error) {
  51. console.log(error)
  52. // 处理请求失败
  53. // wx.showToast({
  54. // title: '请求失败',
  55. // icon: 'error',
  56. // duration: 2000
  57. // })
  58. Notify({ type: 'danger', message: '请求失败' });
  59. reject(error);
  60. },
  61. });
  62. });
  63. }
  64. // 导出请求方法
  65. module.exports = {
  66. get: (url, data, header) => request(url, 'GET', data, header),
  67. post: (url, data, header) => request(url, 'POST', data, header),
  68. // 可以继续添加其他方法,如put, delete等
  69. // ...
  70. };