request.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /** @format */
  2. import store from "@/store";
  3. import config from "@/config";
  4. import { getToken } from "@/utils/auth";
  5. import errorCode from "@/utils/errorCode";
  6. import { toast, showConfirm, tansParams } from "@/utils/common";
  7. let timeout = 600000;
  8. const baseUrl = config.baseUrl;
  9. const request = (config) => {
  10. // 是否需要设置 token
  11. const isToken = (config.headers || {}).isToken === false;
  12. config.header = config.header || {};
  13. if (getToken() && !isToken) {
  14. config.header["Authorization"] = "Bearer " + getToken();
  15. }
  16. // get请求映射params参数
  17. if (config.params) {
  18. let url = config.url + "?" + tansParams(config.params);
  19. url = url.slice(0, -1);
  20. config.url = url;
  21. }
  22. return new Promise((resolve, reject) => {
  23. uni
  24. .request({
  25. method: config.method || "get",
  26. timeout: config.timeout || timeout,
  27. url: config.baseUrl || baseUrl + config.url,
  28. data: config.data,
  29. header: config.header,
  30. dataType: "json",
  31. })
  32. .then((response) => {
  33. let [error, res] = response;
  34. if (error) {
  35. toast("后端接口连接异常");
  36. reject("后端接口连接异常");
  37. return;
  38. }
  39. const code = res.data.code || 200;
  40. const msg = errorCode[code] || res.data.msg || errorCode["default"];
  41. if (code === 401) {
  42. showConfirm(
  43. "登录状态已过期,您可以继续留在该页面,或者重新登录?"
  44. ).then((res) => {
  45. if (res.confirm) {
  46. store.dispatch("LogOut").then((res) => {
  47. uni.reLaunch({ url: "/pages/login" });
  48. });
  49. }
  50. });
  51. reject("无效的会话,或者会话已过期,请重新登录。");
  52. } else if (code === 500) {
  53. toast(msg);
  54. reject("500");
  55. } else if (code !== 200) {
  56. toast(msg);
  57. reject(code);
  58. }
  59. resolve(res.data);
  60. })
  61. .catch((error) => {
  62. let { message } = error;
  63. if (message === "Network Error") {
  64. message = "后端接口连接异常";
  65. } else if (message.includes("timeout")) {
  66. message = "系统接口请求超时";
  67. } else if (message.includes("Request failed with status code")) {
  68. message = "系统接口" + message.substr(message.length - 3) + "异常";
  69. }
  70. toast(message);
  71. reject(error);
  72. });
  73. });
  74. };
  75. export default request;