前端請求分析
vue-admin-template登錄接口請求詳解
在Github拉項目下來運行,Chrome開發者模式調試登錄接口
- 點擊Login按鈕可以發現產生了如下兩個請求
- 點開Login請求,發現傳入的是表單中的用戶名和密碼,返回的是一個
"admin-token"
- 點開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引入進來的
-
從
api\users.js
中引入import { login, logout, getInfo } from '@/api/user'
-
自己聲明的
// 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)的目的
- 發送login請求獲取到token值
- 並存儲到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
我們要進行后端接口數據交互有時候需要改動這里
如何修改
vue.config.js文件改動
- 注釋掉mock.js生成數據
- open屬性改為false,這里是為了編譯啟動項目時不要開兩個網頁
- 如果改了open那么需要在package.json的啟動命令中加上 --open(只在完成編譯后才啟動界面),其中2和3非必須
- 另外需要改動的就是接口的地址
- main.js注釋掉mock生成數據
-
重新編寫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; } }