request.js 2.4 KB

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