当前位置:   article > 正文

前端怎么做一个验证码和JWT,使用mockjs模拟后端

前端怎么做一个验证码和JWT,使用mockjs模拟后端

流程图

创建一个发起请求

创建一个方法

  1. getCaptchaImg() {
  2. this.$axios.get('/captcha').then(res => {
  3. console.log(res);
  4. this.loginForm.token = res.data.data.token
  5. this.captchaImg = res.data.data.captchaImg
  6. console.log(this.captchaImg)
  7. })
  8. },
    captchaImg: "",

创建一个参数

先使页面刷星调用这个方法

  1. created() {
  2. this.getCaptchaImg();
  3. },

要导入的图片,我这里加宽和高是因为,我的显示不出来,也不知道什么原因,望大佬指教

  1. <el-input v-model="loginForm.code">
  2. <el-image slot="append" v-if="captchaImg" :src="captchaImg" style="width: 70px;height: 30px"
  3. class="captchaImg"></el-image>
  4. </el-input>

使用mockjs

在main.js中加入

创建一个mock.js的文件

就可以模拟后端接口

  1. const Mock = require('mockjs')
  2. const Random = Mock.Random
  3. 返回的结果
  4. let Result = {
  5. code: 200,
  6. msg: '操作成功',
  7. data: null
  8. };
  9. 这里和前端对应
  10. Mock.mock('/captcha', 'get', () => {
  11. Result.data = {
  12. token: Random.string(32),
  13. 这些方法可以在mockjs的官网上面去查询
  14. captchaImg: Random.dataImage('100x40', 'p7n5w'),
  15. }
  16. return Result;
  17. });
  18. Mock.mock('/login', 'post', () => {
  19. //无法往header中传入数据
  20. return Result;
  21. });

结果

有点丑,见谅

现在我们要让所有页面都能有JWT

我们就要在store/index.js中进行一个传值

  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. Vue.use(Vuex)
  4. export default new Vuex.Store({
  5. state: {
  6. 设置一个变量token
  7. token: '',
  8. },
  9. getters: {
  10. },
  11. mutations: {
  12. 设置一个方法,将token存入localStorage
  13. SET_TOKEN: (state, token) => {
  14. state.token = token
  15. localStorage.setItem("token", token)
  16. },
  17. },
  18. actions: {
  19. },
  20. modules: {
  21. }
  22. })

写一个发请求的方法

  1. submitForm(loginForm) {
  2. this.$refs[loginForm].validate((valid) => {
  3. if (valid) {
  4. this.$axios.post('/login', this.loginForm).then(res => {
  5. const jwt = res.headers['authorization']
  6. // 把jwt放到请求头中
  7. this.$store.commit('SET_TOKEN', jwt)
  8. //页面的跳转
  9. this.$router.push('/index')
  10. });
  11. } else {
  12. console.log('error submit!!');
  13. return false;
  14. }
  15. });
  16. },

mockjs中写接口

  1. Mock.mock('/login', 'post', () => {
  2. //无法往header中传入数据
  3. return Result;
  4. });

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/921972
推荐阅读
相关标签
  

闽ICP备14008679号