- 這里只寫了一些關(guān)注的點(diǎn)圆恤,比較簡(jiǎn)略,具體還要看網(wǎng)上各位大佬寫的文章和文檔
axios攔截器
- 主要有兩種: 請(qǐng)求攔截器和響應(yīng)攔截器
- 請(qǐng)求: 發(fā)送請(qǐng)求的時(shí)候統(tǒng)一處理,比如要在請(qǐng)求頭headers里加?xùn)|西,如會(huì)話id,token等
let axios2 = axios.create({
timeout: 1000,
});
axios2.interceptors.request.use(
config => {
config.headers.srcChannel = 'KAH';
return config;
},
err => {
return Promise.reject(err);
}
);
- 響應(yīng): 就是后端返回的響應(yīng)進(jìn)行處理沦寂,比如對(duì)errorCode進(jìn)行判斷等
axios2.interceptors.response.use(
response => {
// 攔截響應(yīng),統(tǒng)一處理
if (response.data.errorCode) {
if (response.data.errorCode === '0') {
return response;
}
}
return Promise.reject(response);
},
error => {
return Promise.reject(error)
}
);
axios的主要作用
- axios主要是用于向后臺(tái)發(fā)起請(qǐng)求的淘衙,還有在請(qǐng)求中做更多是可控功能传藏。
axios 配置
- axios defalut 配置
// axios_init.js
import axios from 'axios';
// 設(shè)置默認(rèn)的配置
axios.defaults.headers.testDefault = 'test2';
export default axios;
import axios from 'axios'
import axios_init from './assets/js/axios_init';
export default {
name: 'app',
components: {
// HelloWorld
},
created() {
},
methods: {
test() {
let axios2 = axios.create({
timeout: 1000,
});
axios2.interceptors.request.use(
config => {
config.headers.srcChannel = 'KAH';
return config;
},
err => {
return Promise.reject(err);
}
);
axios2.interceptors.response.use(
response => {
// 攔截響應(yīng),統(tǒng)一處理
if (response.data.errorCode) {
if (response.data.errorCode === '0') {
return response;
}
}
return Promise.reject(response);
},
error => {
return Promise.reject(error)
}
);
axios2.get('/data3.json').then(res => {
console.log(res);
})
axios_init.get('/data2.json').then(res => {
console.log(res);
})
}
}
}
</script>
自定義實(shí)例默認(rèn)值
// 創(chuàng)建實(shí)例時(shí)設(shè)置配置的默認(rèn)值
var instance = axios.create({
baseURL: 'https://api.example.com'
});
// 在實(shí)例已創(chuàng)建后修改默認(rèn)值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
配置的優(yōu)先順序
配置會(huì)以一個(gè)優(yōu)先順序進(jìn)行合并彤守。這個(gè)順序是:在 lib/defaults.js 找到的庫(kù)的默認(rèn)值毯侦,然后是實(shí)例的 defaults 屬性,最后是請(qǐng)求的 config 參數(shù)具垫。后者將優(yōu)先于前者叫惊。這里是一個(gè)例子:
// 使用由庫(kù)提供的配置的默認(rèn)值來創(chuàng)建實(shí)例
// 此時(shí)超時(shí)配置的默認(rèn)值是 `0`
var instance = axios.create();
// 覆寫庫(kù)的超時(shí)默認(rèn)值
// 現(xiàn)在,在超時(shí)前做修,所有請(qǐng)求都會(huì)等待 2.5 秒
instance.defaults.timeout = 2500;
// 為已知需要花費(fèi)很長(zhǎng)時(shí)間的請(qǐng)求覆寫超時(shí)設(shè)置
instance.get('/longRequest', {
timeout: 5000
});