request.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. const baseUrl="https://helper.qcfun.ximengnaikang.cn/api";
  2. // const baseUrl="http://192.168.0.15/api";
  3. import store from "../store/store.js"
  4. const request=function(url,dataPraams,method="POST"){
  5. const token = uni.getStorageSync("token")
  6. let header={}
  7. const whiteUrl=["/user/getopenidtoken",""];
  8. if(whiteUrl.indexOf(url)==-1){
  9. header["authorization"]="bearer "+token
  10. }
  11. url=baseUrl+url;
  12. if(!store.state.updateUser){
  13. // 显示loading
  14. uni.showLoading({
  15. title: '加载中'
  16. });
  17. }
  18. store.state.updateUser=false
  19. return new Promise((resolve,reject)=>{
  20. uni.request({
  21. url,
  22. method,
  23. data:dataPraams,
  24. header,
  25. success:function(res){
  26. uni.hideLoading();
  27. const {data}=res
  28. const {error_code}=data
  29. // 存在token 进行刷新
  30. if(res.header.Authorization){
  31. let token=res.header.Authorization;
  32. if(token){
  33. token=token.substr(7);
  34. uni.setStorage({
  35. key:"token",
  36. data:token
  37. })
  38. store.commit("change_token",token)
  39. }
  40. }
  41. if(error_code===200){
  42. resolve(data)
  43. }else{
  44. if(error_code === 413){
  45. uni.removeStorage({
  46. key:"userinfo",
  47. success:function(res){
  48. uni.showToast({
  49. title:"token过期,请退出重新登录",
  50. icon:"none",
  51. duration: 2500
  52. })
  53. }
  54. })
  55. }else if(error_code === 42201){
  56. resolve(data)
  57. }else{
  58. let msg=data.message ? data.message : '服务器错误'
  59. msg = data.msg ? data.msg : msg
  60. uni.showToast({
  61. title:msg,
  62. icon:"none",
  63. duration: 2500
  64. })
  65. }
  66. reject(data)
  67. }
  68. },
  69. fail:function(err){
  70. uni.hideLoading();
  71. uni.showToast({
  72. title:"网络加载失败",
  73. icon:"none",
  74. duration: 2500
  75. })
  76. reject(err)
  77. }
  78. })
  79. })
  80. }
  81. export default request;