request.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // 全局请求封装
  2. const base_url = 'http://localhost:996'
  3. // 需要修改token,和根据实际修改请求头
  4. export default (params) => {
  5. let url = params.url;
  6. let method = params.method || "get";
  7. let data = params.data || {};
  8. let header = {}
  9. if (method === "post") {
  10. header = {
  11. 'Content-Type': 'application/json'
  12. };
  13. }
  14. // 获取本地token
  15. if (uni.getStorageSync("token")) {
  16. header['Authorization'] = 'Bearer ' + uni.getStorageSync("token");
  17. }
  18. return new Promise((resolve, reject) => {
  19. uni.request({
  20. url: base_url + url,
  21. method: method,
  22. header: header,
  23. data: data,
  24. success(response) {
  25. const res = response
  26. // 根据返回的状态码做出对应的操作
  27. //获取成功
  28. console.log(res.statusCode);
  29. if (res.statusCode == 200) {
  30. resolve(res.data);
  31. } else {
  32. uni.clearStorageSync()
  33. switch (res.statusCode) {
  34. case 401:
  35. uni.showModal({
  36. title: "提示",
  37. content: "请登录",
  38. showCancel: false,
  39. success(res) {
  40. setTimeout(() => {
  41. uni.navigateTo({
  42. url: "/pages/login/index",
  43. })
  44. }, 1000);
  45. },
  46. });
  47. break;
  48. case 404:
  49. uni.showToast({
  50. title: '请求地址不存在...',
  51. duration: 2000,
  52. })
  53. break;
  54. default:
  55. uni.showToast({
  56. title: '请重试...',
  57. duration: 2000,
  58. })
  59. break;
  60. }
  61. }
  62. },
  63. fail(err) {
  64. console.log(err)
  65. if (err.errMsg.indexOf('request:fail') !== -1) {
  66. wx.showToast({
  67. title: '网络异常',
  68. icon: "error",
  69. duration: 2000
  70. })
  71. } else {
  72. wx.showToast({
  73. title: '未知异常',
  74. duration: 2000
  75. })
  76. }
  77. reject(err);
  78. },
  79. complete() {
  80. // 不管成功还是失败都会执行
  81. uni.hideLoading();
  82. uni.hideToast();
  83. }
  84. });
  85. }).catch((e) => {
  86. });
  87. };