1. 程式人生 > 實用技巧 >vue-admin-template結合Spring Boot登入

vue-admin-template結合Spring Boot登入

前端請求分析

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;
        }
    }