1
0

request.js 1.7 KB

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