从零开始摸索VUE,配合Golang搭建导航网站(二十七.vue-admin-template完善前端登陆逻辑)

「这是我参与11月更文挑战的第27天,活动详情查看:2021最后一次更文挑战

前言

前面完成了后端的登录,退出登录,获取token信息的逻辑,现在要对接这些后端接口,整体调试。

修改全局请求配置

全局请求配置位置在src/utils/reqeusts.js,这里有一个可以叫拦截器,前端所有的请求响应都会在这里。 后端的接口消息同一都是msg,而这个文件里面是message,需要修改,不然后端的报错前端显示不出来。vue-admin-template默认鉴权失败状态码为50008,50012,假如改后端的状态码Gin框架会报错,会说不符合规范,我统一改成50X:,默认的MessageBox.confirmtoken过期弹框我改成中文内容:

response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 401) {
        // to re-login
        MessageBox.confirm('登录状态已经过期', '登录已过期', {
          confirmButtonText: '重新登陆',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    Message({
      message: error,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
复制代码

实现的效果:
故意登录失败:

image.png 故意使token失效请求数据接口:

image.png 最终要是被拦截了

登录设置token

登陆过后所有的请求都需要设置token,文件位置:src/store/modules/user.js: 这些token最终被存在cookie:

image.png image.png

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data)
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

复制代码

成功后登录的数据库的数据:

image.png 每次接口请求token验证成功后,后端逻辑都会对token过期时间增加7200秒,也就是两个小时。首次登录会对没有的token的账号进行生成token然后返回token给前端保存到cookie中。
接下来的所有的接口的请求头header都会携带这个token:

image.png

用户信息显示

需要显示一个右上角的信息,那就涉及到了info接口,文件位置在:src/store/modules/user.js 根据接口字段改成大写

image.png

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { Name, Avatar } = data

        commit('SET_NAME', Name)
        commit('SET_AVATAR', Avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
复制代码

总结

前端主要是针对后端的格式进行调整,修改字段的大小写和状态码,还有一个英文调试信息改成中文,都很简单。因为在登录的时候为了安全问题,主要逻辑都在后端处理,前端所有的代码都在用户面前,其实还有优化的地方,例如验证码,robots文件,验证码密码强度,为了快速上线的确省略了很多地方,虽说简单但是还是全部使自己的实现了基本所有的代码,知道了基本所有细节,学到东西了,下篇准备把这个完善后台CI脚本,真实上线。

Guess you like

Origin juejin.im/post/7035158665489285133