request.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import env from '../js/env.js';
  2. function service(options = {}) {
  3. let baseUrl = env.getBaseUrl()
  4. options.url = baseUrl + `${options.url}`;
  5. // options.url = `${env.baseUrl}${options.url}`;
  6. // 判断本地是否存在token,如果存在则带上请求头
  7. let access_token = uni.getStorageSync('accessToken')
  8. let refresh_token = uni.getStorageSync('refresh_token')
  9. if(options.header&&options.header['content-type']){
  10. options.header['Authorization'] ='Bearer '+ access_token
  11. }else {
  12. options.header = {
  13. 'Authorization': 'Bearer '+ access_token,
  14. 'content-type':'application/json'
  15. };
  16. }
  17. // resolved是返回成功数据,rejected返回错误数据
  18. return new Promise((resolved, rejected) => {
  19. options.success = (res) => {
  20. // 如果请求回来的状态码不是200则执行以下操作
  21. if (res.data.code !== 200) {
  22. // 非成功状态码弹窗
  23. console.log('错误信息:+++',res.data.msg)
  24. // 这里可以做一些状态码判断以及操作
  25. if(res.data.code === 401){
  26. uni.showToast({
  27. icon: 'none',
  28. duration: 3000,
  29. title: '登录过期,即将跳转登录页'
  30. });
  31. setTimeout(()=>{
  32. uni.navigateTo({
  33. url:'/pages/login/login'
  34. })
  35. },3000)
  36. }else{
  37. uni.showToast({
  38. icon: 'none',
  39. duration: 3000,
  40. title: res.data.msg || '系统繁忙,请重试!'
  41. });
  42. }
  43. // 返回错误信息
  44. rejected(res)
  45. } else {
  46. // 请求回来的状态码为200则返回内容
  47. resolved(res)
  48. }
  49. };
  50. options.fail = (err) => {
  51. console.log('错误信息:+++',err)
  52. // 请求失败弹窗
  53. uni.showToast({
  54. icon: 'none',
  55. duration: 3000,
  56. title: '服务器连接失败,请检查网络'
  57. });
  58. rejected(err);
  59. };
  60. uni.request(options);
  61. });
  62. }
  63. export default service;