axios特點
- 基于promise封裝的異步請求庫
- 瀏覽器端/node端都可以使用
- 支持請求/響應(yīng)攔截器
- 支持請求取消
- 支持請求/響應(yīng)數(shù)據(jù)轉(zhuǎn)換 JSON.parse||stringify
- 批量發(fā)送多個請求 (promise.all([...]))
axios.create(config)
- 根據(jù)指定配置創(chuàng)建一個新的axios,也就是每個axios都有自己的配置。
- 新axios只是沒有取消請求和批量發(fā)請求的方法,其他所有語法都是一致的。
為什么要設(shè)計這個語法?
需求:項目中部分接口的主域名有差別,配置不太一樣,如何處理?
解決:創(chuàng)建兩個新axios,每個都有自己特有的配置,分別應(yīng)用到不同要求的請求中。
實例
// 第一個axios
const ins = axios.create({
baseURL: 'http://localhost:3000'
})
// 第二個axios
const ins2 = axios.create({
baseURL: 'http://localhost:4000'
})
// 使用第一個axios
async function test() {
ins({
url: '/posts',
params: {
id: 2
}
})
}
// 使用第二個axios
async function test2() {
ins2({
url: '/posts',
params: {
id: 2
}
})
}
請求攔截器 、 響應(yīng)攔截器
axios.interceptors.request.use() 請求攔截器(先定義后執(zhí)行,源碼中使用unshift)
axios.interceptors.request.use(
config => {
return config
},
err => {
return err
}
)
axios.interceptors.response.use() 響應(yīng)攔截器(順序執(zhí)行,源碼中使用push)
axios.interceptors.response.use(
response => {
return response
},
err => {
return err
}
)
為了讓promise鏈延續(xù),一定要將結(jié)果返回。
取消請求
- 在請求的配置對象中
cancelToken: new axios.CancelToken((c)=>{cancel = c}), c是用于取消請求的函數(shù)。
let cancel; // 用于儲存取消請求的函數(shù)
// 發(fā)送請求的函數(shù)
function getSome(){
axios({
url:'localhost:4000/getsome',
cancelToken:new axios.CancelToken((c)=>{
cancel = c
})
}).then( response => {
cancel = null //請求成功則將取消請求的函數(shù)賦值為null
} ).catch(error => {
cancel = null
console.log(error.message) //如果取消請求則會輸出該內(nèi)容
})
}
// 取消請求的函數(shù)
function cancelReq(){
if(typeof cancel === 'function'){
cancel()
}else{
console.log(‘當前沒有正在執(zhí)行的請求~’)
}
}
判斷錯誤是否由取消請求引起
axios.isCancel(error)
if(axios.isCancel(error)){
console.log('請求取消~!')
}else{
console.log('請求錯誤~!')
}