axios 二次封裝
基本上每一個(gè)項(xiàng)目開發(fā),都必須要二次封裝 axios。主要是為了減少重復(fù)性工作,不可能每一次發(fā)起新請求時(shí),都要重新配置請求域名、請求頭 Content-Type、Token 等信息。所以需要把公用的部分都封裝成一個(gè)函數(shù),每次調(diào)用的時(shí)候只需要傳入變化的參數(shù)。
:::warning 注意
基于上個(gè)案例在繼續(xù)做優(yōu)化,如需要請查看 axios 響應(yīng)攔截器。
:::
封裝
src/plugins/axios.js
import axios from 'axios'
import qs from 'qs'
/**
* 請求攔截器
*/
axios.interceptors.request.use((config) => {
config.data = qs.stringify(config.data)
return config
})
/**
* 響應(yīng)攔截器
*/
axios.interceptors.response.use((response) => {
if (response.data.code !== 200) {
alert('接口響應(yīng)失敗')
}
return response.data
})
/**
* 接口請求方法
*/
const request = (method, option) => {
return axios({
method: method,
url: 'https://study.noxussj.top' + option.url,
data: option.data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
}
export default {
get: (option) => request('get', option),
post: (option) => request('post', option),
put: (option) => request('put', option)
}
調(diào)用
這樣每次發(fā)起請求時(shí),只需要把 二次封裝的 axios 引入進(jìn)來使用即可??梢源蠓鶞p少代碼數(shù)量。文章來源:http://www.zghlxwxcb.cn/news/detail-673082.html
import axios from './plugins/axios.js'
/**
* 發(fā)起請求
*/
const p1 = axios.post({
url: '/api/login',
data: { account: 'test', password: '123456' }
})
p1.then((res) => {
console.log(res.data)
})
原文鏈接:菜園前端文章來源地址http://www.zghlxwxcb.cn/news/detail-673082.html
到了這里,關(guān)于axios 二次封裝的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!