vue項(xiàng)目實(shí)戰(zhàn)之優(yōu)雅使用axios
axios傳參
params與data傳參
- params 傳參:參數(shù)以 k=v&k=v 格式放置在 url 中傳遞。
springboot后端可以使用@RequestParam注解接受請(qǐng)求,或者保證參數(shù)名跟k一樣時(shí)也可以接收到
只要是使用params傳參,無(wú)論是post請(qǐng)求還是get請(qǐng)求都是拼接都url中,此時(shí)的post請(qǐng)求也只是偽post請(qǐng)求
- data傳參:參數(shù)被放在請(qǐng)求體中。
后端必須使用@RequestBody來(lái)接收,否則會(huì)接收不到,因?yàn)閍xios默認(rèn)傳遞的參數(shù)類(lèi)型是application/json,會(huì)將其轉(zhuǎn)成json格式。
舉例:
vue中:
export function login(account, password, orgType) {
return request({
url: '/webapi/login',
method: 'post',
data: {"loginId":account,"password":password,"orgType":orgType}
)}
則會(huì)轉(zhuǎn)成json格式放入請(qǐng)求體中

如果后端中想這樣接收,是接收不到的,因?yàn)榇藭r(shí)后端的接收格式是application/x-www-form-urlencoded
@PostMapping(value = "/login")
public Result login(String loginId, String password, int orgType, HttpServletResponse response){
}
如果我們使用data傳參,但后端不想使用@RequesBody的方式來(lái)接收,那怎么處理呢?
首先要設(shè)置請(qǐng)求頭
headers: {
//關(guān)鍵
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
直接拼接成k=v
適用參數(shù)較少的情況
export function login(account, password, orgType) {return request({
url: '/webapi/login',
method: 'post',
data: "loginId="+account+ "&password="+password+"&orgType="+orgType
})
}
使用qs實(shí)現(xiàn) json 對(duì)象的 k=v 格式化
適用參數(shù)較多的情況
安裝qs : npm install qs
import qs form 'qs'
export function login(account, password, orgType) {
return request({
url: '/webapi/login',
method: 'post',
data: qs.stringify({"loginId":account, "password":password,"orgType":orgType})
})
}
這樣后端就可以這樣接收了:
@PostMapping(value = "/login")
public Result login(String loginId, String password, int orgType, HttpServletResponse response){
}
封裝axios
設(shè)置request攔截器,可以在這里添加token,這樣每次發(fā)起請(qǐng)求時(shí)都會(huì)攜帶token了
設(shè)置響應(yīng)攔截器,根據(jù)后端的狀態(tài)碼進(jìn)行相應(yīng)處理,比如但發(fā)現(xiàn)token失效后,就跳轉(zhuǎn)到登錄頁(yè)面等
import axios from 'axios'
import { Notification, MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 創(chuàng)建axios實(shí)例
const service = axios.create({
// axios中請(qǐng)求配置有baseURL選項(xiàng),表示請(qǐng)求URL公共部分
baseURL: "http://localhost:8082",
// 超時(shí)
timeout: 10000
})
// request攔截器
service.interceptors.request.use(config => {
// 是否需要設(shè)置 token
const isToken = (config.headers || {}).isToken === false
if (getToken() && !isToken) {
config.headers['Authorization'] = 'Bearer ' + getToken() // 讓每個(gè)請(qǐng)求攜帶自定義token 請(qǐng)根據(jù)實(shí)際情況自行修改
}
return config
}, error => {
console.log(error)
Promise.reject(error)
})
// 響應(yīng)攔截器
service.interceptors.response.use(res => {
// 未設(shè)置狀態(tài)碼則默認(rèn)成功狀態(tài)
const code = res.data.code || 200;
// 獲取錯(cuò)誤信息
const msg = errorCode[code] || res.data.msg || errorCode['default']
if (code === 401) {
MessageBox.confirm('登錄狀態(tài)已過(guò)期,您可以繼續(xù)留在該頁(yè)面,或者重新登錄', '系統(tǒng)提示', {
confirmButtonText: '重新登錄',
cancelButtonText: '取消',
type: 'warning'
}
).then(() => {
store.dispatch('LogOut').then(() => {
location.href = '/index';
})
}).catch(() => {});
} else if (code === 500) {
Message({
message: msg,
type: 'error'
})
return Promise.reject(new Error(msg))
} else if (code !== 200) {
Notification.error({
title: msg
})
return Promise.reject('error')
} else {
return res.data
}
},
error => {
console.log('err' + error)
let { message } = error;
if (message == "Network Error") {
message = "后端接口連接異常";
}
else if (message.includes("timeout")) {
message = "系統(tǒng)接口請(qǐng)求超時(shí)";
}
else if (message.includes("Request failed with status code")) {
message = "系統(tǒng)接口" + message.substr(message.length - 3) + "異常";
}
Message({
message: message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export default service
使用
import request from './request'
export function apiLogin(data){
return request({
url:'/user/login',
method:'post',
data:data
})
}
參考鏈接:http://www.dbjr.com.cn/article/237137.htm
總結(jié)
到此這篇關(guān)于vue項(xiàng)目實(shí)戰(zhàn)之優(yōu)雅使用axios的文章就介紹到這了,更多相關(guān)vue優(yōu)雅使用axios內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談Vue中的this.$store.state.xx.xx
這篇文章主要介紹了Vue中的this.$store.state.xx.xx用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
Vue el使用el-checkbox-group復(fù)選框進(jìn)行單選框方式
這篇文章主要介紹了Vue el使用el-checkbox-group復(fù)選框進(jìn)行單選框方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10
vue3中使用@vueuse/core中的圖片懶加載案例詳解
這篇文章主要介紹了vue3中使用@vueuse/core中的圖片懶加載案例,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03
Vue+Bootstrap實(shí)現(xiàn)簡(jiǎn)易學(xué)生管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Vue+Bootstrap實(shí)現(xiàn)簡(jiǎn)易學(xué)生管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-02-02
vue?退出登錄?清除localStorage的問(wèn)題
這篇文章主要介紹了vue?退出登錄?清除localStorage的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
element組件el-date-picker禁用當(dāng)前時(shí)分秒之前的日期時(shí)間選擇
本文主要介紹了element組件el-date-picker禁用當(dāng)前時(shí)分秒之前的日期時(shí)間選擇,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01

