Http.js

  1. import Vue from "vue";
  2. import axios from "axios";
  3. import router from "@/router/router";
  4. // import qs from "querystring";
  5. import { getSession, Ddebounce, removeSession } from "@/utils/utils.js";
  6. // loading对象
  7. let loading = null;
  8. // 当前正在请求的数量
  9. let needLoadingRequestCount = 0;
  10. // 显示loading
  11. function showLoading() {
  12. if (needLoadingRequestCount === 0 && !loading) {
  13. loading = Vue.prototype.$loading({
  14. lock: true,
  15. text: "请求中,请稍等...",
  16. spinner: "el-icon-loading",
  17. background: "rgba(0, 0, 0, 0.7)"
  18. });
  19. }
  20. needLoadingRequestCount++;
  21. }
  22. // 隐藏loading
  23. function hideLoading() {
  24. needLoadingRequestCount--;
  25. needLoadingRequestCount = Math.max(needLoadingRequestCount, 0);
  26. if (needLoadingRequestCount === 0) {
  27. toHideLoading();
  28. }
  29. }
  30. let toHideLoading = Ddebounce(() => {
  31. loading && loading.close();
  32. loading = null;
  33. }, 500, false);
  34. const service = axios.create({
  35. baseURL: "http://xxx.com", // 默认的地址
  36. timeout: 30000, // 请求超时时间
  37. headers: {},
  38. });
  39. // 请求拦截器
  40. service.interceptors.request.use(
  41. config => {
  42. config.headers = Object.assign(config.headers, { "ADMIN-TOKEN": getSession('token') || "" })
  43. // 判断当前请求是否设置了不显示 Loading
  44. if (config.headers.showLoading !== false) {
  45. showLoading(config.headers.loadingTarget);
  46. }
  47. // 返回图片流方式处理
  48. if (config.url.includes("/login/captcha")) {
  49. config.responseType = "arraybuffer"
  50. }
  51. if (config.method.toLocaleLowerCase() === "get" || config.method.toLocaleLowerCase() === "delete") {
  52. config.params = config.data;
  53. }
  54. return config;
  55. },
  56. error => {
  57. // 判断当前请求是否设置了不显示 Loading
  58. if (error.config.headers.showLoading !== false) {
  59. hideLoading();
  60. }
  61. return Promise.reject(error);
  62. }
  63. );
  64. // 返回拦截器
  65. service.interceptors.response.use(
  66. config => {
  67. // 判断当前请求是否设置了不显示 Loading
  68. if (config.headers.showLoading !== false) {
  69. hideLoading();
  70. }
  71. // 签名过期情况处理
  72. if (config.data.code === 10100) {
  73. removeSession("token");
  74. router.push("/login");
  75. }
  76. return config;
  77. },
  78. error => {
  79. // 判断当前请求是否设置了不显示 Loading
  80. if (error.config.headers.showLoading !== false) {
  81. hideLoading();
  82. }
  83. return Promise.reject(error);
  84. }
  85. );
  86. // 挂载请求
  87. Vue.prototype.$axios = service;
  88. // 请求统一处理
  89. function requst(options) {
  90. return new Promise((resolve, reject) => {
  91. options
  92. .then(res => {
  93. // 返回图片流方式处理
  94. if (res.config.url.includes("/login/captcha")) {
  95. resolve('data:image/png;base64,' + btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), '')))
  96. } else {
  97. if (res.data?.code == 0) {
  98. resolve(res.data);
  99. } else {
  100. reject(res.data.msg || res.data.Msg || "加载数据超时,请稍后重试");
  101. }
  102. }
  103. })
  104. .catch(error => {
  105. if (error.message.includes(`timeout of ${error.config.timeout}ms exceeded`)) {
  106. reject("加载数据超时,请稍后重试");
  107. } else {
  108. reject(error);
  109. }
  110. });
  111. });
  112. }
  113. // get.post.put.del.patch请求方法提取
  114. const get = (url, params, showLoading = true) => {
  115. return requst(service.get(url, { data: params }, { headers: { showLoading } }));
  116. };
  117. const post = (url, params, showLoading = true) => {
  118. return requst(service.post(url, params, { headers: { showLoading } }));
  119. };
  120. const put = (url, params, showLoading = true) => {
  121. return requst(service.put(url, params, { headers: { showLoading } }));
  122. };
  123. const del = (url, params, showLoading = true) => {
  124. return requst(
  125. service.delete(url, { data: params }, { headers: { showLoading } })
  126. );
  127. };
  128. const patch = (url, params, showLoading = true) => {
  129. return requst(service.patch(url, { data: params }, { headers: { showLoading } }));
  130. };
  131. export default requst;
  132. export { get, post, put, del, patch };

Login.Request.js

  1. // 根据模块封装
  2. import { get, post } from "../Http";
  3. export default {
  4. /**
  5. * @method 获取登录图像验证码
  6. * @param {*} key 随机数
  7. */
  8. getCodeImage: params =>
  9. get(`/login/captcha?key=${params}`, "", false),
  10. /**
  11. * @method 获取图形验证码
  12. * @param {*} key 随机数
  13. */
  14. checkLoginCode: params =>
  15. get(`/login/check`, params, false),
  16. /**
  17. * @method 登录验证
  18. * @param {*} name 登录名
  19. * @param {*} password 密码
  20. * @param {*} code 验证码
  21. */
  22. login: params =>
  23. post(`/login`, params, false),
  24. /**
  25. * @method 退出登录
  26. * @param {*}
  27. */
  28. logout: params =>
  29. post(`/logout`, params, false),
  30. }

Login.vue 测试

  1. <template>
  2. <div class="login-wrap">
  3. <div class="ms-login">
  4. <div class="ms-title">{{ adminTitle }}</div>
  5. <el-form :model="form" :rules="rules" ref="ruleForm" label-width="0px" class="ms-content">
  6. <el-form-item prop="username">
  7. <el-input v-model="form.name" placeholder="请输入用户名称" clearable></el-input>
  8. </el-form-item>
  9. <el-form-item prop="password">
  10. <el-input
  11. type="password"
  12. placeholder="请输入密码"
  13. v-model="form.password"
  14. show-password
  15. clearable
  16. maxlength="20"
  17. show-word-limit
  18. ></el-input>
  19. </el-form-item>
  20. <el-form-item label prop="code">
  21. <div class="disflex flexdr">
  22. <el-input placeholder="请输入验证码" v-model="form.code" clearable></el-input>
  23. <el-image @click="refreshCode" :src="codeImage" alt class="codeImage">
  24. <div slot="error" class="image-slot">
  25. <i class="el-icon-picture-outline"></i>
  26. </div>
  27. </el-image>
  28. </div>
  29. </el-form-item>
  30. <div class="login-btn">
  31. <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
  32. </div>
  33. </el-form>
  34. </div>
  35. </div>
  36. </template>
  37. <script>
  38. import LoginAjax from "@/utils/https/modules/Login.request.js";
  39. import { generateString, setSession } from "@/utils/utils.js";
  40. export default {
  41. data() {
  42. return {
  43. adminTitle: "xxx 用户后台",
  44. form: {
  45. name: "",
  46. password: "",
  47. code: ""
  48. },
  49. rules: {
  50. name: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
  51. password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  52. code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
  53. },
  54. codeImage: "",
  55. codeKey: generateString("xxxxxxxxxxx")
  56. };
  57. },
  58. methods: {
  59. // 刷新验证码
  60. async refreshCode() {
  61. try {
  62. this.codeImage = "";
  63. this.codeKey = generateString("xxxxxxxxxx");
  64. this.codeImage = await LoginAjax.getCodeImage(this.codeKey);
  65. } catch (error) {
  66. this.$message.error(error);
  67. }
  68. },
  69. // 登录
  70. submitForm(formName) {
  71. this.$refs[formName].validate(async valid => {
  72. if (valid) {
  73. try {
  74. const { data, msg } = await LoginAjax.login({
  75. key: this.codeKey,
  76. ...this.form
  77. });
  78. setSession("xxxtoken", data);
  79. this.$message.success(msg);
  80. this.$router.push("/activity");
  81. } catch (error) {
  82. this.refreshCode();
  83. this.form.code = "";
  84. return false;
  85. }
  86. } else {
  87. return false;
  88. }
  89. });
  90. }
  91. },
  92. mounted() {
  93. this.$nextTick(() => {
  94. this.refreshCode();
  95. });
  96. }
  97. };
  98. </script>
  99. <style lang="scss" scoped>
  100. // ...
  101. </style>