request.js 1.9 KB

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