request.js 2.0 KB

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