首页 > 技术文章 > vue-admin-template结合Spring Boot登录

iamfatotaku 2020-11-29 21:15 原文

前端请求分析

vue-admin-template登录接口请求详解

在Github拉项目下来运行,Chrome开发者模式调试登录接口

  1. 点击Login按钮可以发现产生了如下两个请求

  1. 点开Login请求,发现传入的是表单中的用户名和密码,返回的是一个"admin-token"

  1. 点开info请求,传入的是前面的token,返回的是如下的信息

vue-admin-template登录接口代码详解

打开\src\views\login\index.vue,可以看到有一个handleLogin方法,专门用来处理登录校验的信息:

handleLogin() {
    this.$refs.loginForm.validate(valid => {
        if (valid) {
            this.loading = true
            this.$store.dispatch('user/login', this.loginForm).then(() => {
                this.$router.push({ path: this.redirect || '/' })
                this.loading = false
            }).catch(() => {
                this.loading = false
            })
        } else {
            console.log('error submit!!')
            return false
        }
    })
}

可以看到他dispatch到了'user/login',我们找到modeules\user.js地方:

这里有两个login方法,第一个方法是user.js中声明的,第二个方法可以在顶部看到是src目录下的api文件夹中的user.js引入进来的

  1. api\users.js中引入

    import { login, logout, getInfo } from '@/api/user'
    
  2. 自己声明的

    // 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
                // 调用SET_TOKEN方法,将返回值里的token设置到resp里
                commit('SET_TOKEN', data.token)
                setToken(data.token)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },
    

首先先分析本文件中的login,在分析之前,先讲一下什么是Promise

Promise是异步编程的一种解决方案,它有三种状态,分别是pending-进行中resolved-已完成rejected-已失败

当Promise的状态又pending转变为resolved或rejected时,会执行相应的方法,并且状态一旦改变,就无法再次改变状态,这也是它名字promise-承诺的由来

点开下面的这个login,可以看到实际上就是去找了api中的那个login,所以我们进入了api\user.js,此时我们再点开这个request,可以发现他实际上就是封装了一个axios请求

import request from '@/utils/request'

export function login(data) {
  return request({
    url: '/vue-admin-template/user/login',
    method: 'post',
    data
  })
}
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

看到这里也就不难明白转发(dispatch)的目的

  1. 发送login请求获取到token值
  2. 并存储到Vuex状态管理模式中,供多个组件同时识别使用

响应数据分析

数据的相应也在api/user.js中可以找到拦截器

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

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

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

可以看到如果不是20000就代表了出错,此外50008、50012和50014是由特殊意义的错误编码

登录接口请求头详解

在项目的根目录下有vue.config.js

可以看到默认端口的设置

// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || process.env.npm_config_port || 9528 // dev port

然后打开.dev.environment,可以看到开发环境的配置:

# just a flag
ENV = 'development'

# base api
VUE_APP_BASE_API = '/dev-api'

上面可以看到之前的VUE_APP_BASE_API

我们要进行后端接口数据交互有时候需要改动这里

如何修改

いってらしゃい(您走好下次再来)ノ (cnblogs.com)

vue.config.js文件改动

  1. 注释掉mock.js生成数据
  2. open属性改为false,这里是为了编译启动项目时不要开两个网页

  1. 如果改了open那么需要在package.json的启动命令中加上 --open(只在完成编译后才启动界面),其中2和3非必须

  1. 另外需要改动的就是接口的地址

  1. main.js注释掉mock生成数据

  1. 重新编写Controller中的方法,可以看到已经从Spring Boot获取数据了

    @Slf4j
    @Controller
    @RequestMapping(value = "/authentication")
    public class AuthenticationController {
        @CrossOrigin
        @PostMapping(value = "/login")
        @ResponseBody
        public Map login() {
            HashMap<String, Object> response = new HashMap<>();
            HashMap<String, Object> responseData = new HashMap<>();
            responseData.put("token", 1);
            response.put("code", 20000);
            response.put("msg", "登录成功");
            response.put("data", responseData);
            return response;
        }
    
        @CrossOrigin
        @GetMapping(value = "/info")
        @ResponseBody
        public Map info() {
            HashMap<String, Object> responseInfo = new HashMap<>();
            HashMap<String, Object> responseData = new HashMap<>();
            responseData.put("roles", "admin");
            responseData.put("name", "Super admin");
            responseData.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            responseInfo.put("code", 20000);
            responseInfo.put("msg", "登录成功");
            responseInfo.put("data", responseData);
            return responseInfo;
        }
    }
    

推荐阅读