request.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // import config from './config.js';
  2. const request = (url = '', method = 'GET', data = {}, header = { //这里这样封装是为了后续具体组件中使用时可以直接传参,需按此顺序传参;而不需要写url:xxx等键值对传参
  3. //具体的header和后端商同后再编写,这里以常见的token为例
  4. 'Authorization': 'Bearer '+ (uni.getStorageSync('token') ? uni.getStorageSync('token') : ''),
  5. }) => {
  6. return new Promise((resolve, reject) => {
  7. // console.log(header);
  8. uni.request({
  9. url: 'http://10.3.13.84:7003' + url, //接口地址:前缀+方法中传入的地址
  10. method: method, //请求方法
  11. data: data, //传递参数
  12. header: header, //自定义头部,和后端商同后编写
  13. success: (res) => {
  14. // console.log('request.js文件的通用接口请求封装返回的结果数据',res);
  15. //注:因为这里对请求成功的没有统一设置抛错提示,所以后续具体组件中使用接口请求的res除200(实际以后端同事定好的为准)成功外的其他code需要额外写抛错提示
  16. if (res.data.code == 405) { //自定请求失败的情况,这里以常见的token失效或过期为例
  17. uni.removeStorageSync('token');
  18. uni.showModal({
  19. showCancel: false,
  20. title: '温馨提示',
  21. content: res.data.msg,
  22. success: function(result) {
  23. if (result.confirm) {
  24. uni.reLaunch({
  25. url: '/pages/login/login' //这里需用绝对路径才可
  26. });
  27. }
  28. }
  29. });
  30. }
  31. resolve(res.data) //成功
  32. },
  33. // 这里的接口请求,如果出现问题就输出接口请求失败的msg;
  34. //注:因为这里对于请求失败的设置统一抛错提示了,所以后续具体组件中使用接口请求的catch中不需要再写抛错提示
  35. fail: (err) => {
  36. uni.showToast({
  37. title: "" + err.msg,
  38. icon: 'none'
  39. });
  40. reject(err)
  41. }
  42. })
  43. })
  44. }
  45. export default request;