目錄
1、項(xiàng)目中引入Axios
2、使用Axios發(fā)送請(qǐng)求
2.1、例:發(fā)送GET請(qǐng)求
2.2、例:發(fā)送POST請(qǐng)求
3、axios并發(fā)請(qǐng)求
4、攔截器
1、項(xiàng)目中引入Axios
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
注:個(gè)人學(xué)習(xí)筆記,因自己學(xué)過(guò)后端,所以有關(guān)后端的代碼,我在這里就不展示了~
不了解后端的寶子,也不會(huì)耽誤學(xué)習(xí),因?yàn)楣纠飼?huì)有寫(xiě)好的接口文檔,直接使用就可以了
2、使用Axios發(fā)送請(qǐng)求
2.1、例:發(fā)送GET請(qǐng)求
axios.get("http://localhost:8080/user?id=1").then(function(res) {
console.log(res);
}).catch(function(error){
console.log(error);
});
// es6中簡(jiǎn)化寫(xiě)法:lambada表達(dá)式
axios.get("http://localhost:8080/user?id=2").then((res)=> {
console.log(res);
}).catch((error)=> {
console.log(error);
});
?格式其實(shí)還是挺簡(jiǎn)單的~
2.2、例:發(fā)送POST請(qǐng)求
axios.post("http://localhost:8080/user",{
name:"xxx",
age:10
}).then((res)=> {
console.log(res);
}).catch((error)=> {
console.log(error);
});
3、axios并發(fā)請(qǐng)求
并發(fā)請(qǐng)求:將多個(gè)請(qǐng)求在同一時(shí)刻發(fā)送到后端服務(wù)接口,最后在集中處理每個(gè)請(qǐng)求的響應(yīng)結(jié)果
代碼:
function test1() {
return axios.get("http://localhost:8080/user?id=3");
}
function test2() {
return axios.get("http://localhost:8080/user?id=4");
}
axios.all([test1(),test2()]).then(
axios.spread((res_test1,res_test2)=> {
console.log(res_test1);
console.log(res_test2);
})
);
4、攔截器
- 作用:用來(lái)將axios中共有參數(shù),響應(yīng)公共處理交給攔截處理,減少axios發(fā)送請(qǐng)求時(shí)代碼冗余
- 類型:請(qǐng)求攔截器;響應(yīng)攔截器
使用:
//創(chuàng)建axios的配置對(duì)象
var instance = axios.create({
baseURL:"http://localhost:8080/",
timeout:5000
});
//請(qǐng)求攔截器
instance.interceptors.request.use(function(config) {
config.url += "?token=1111"
return config;
});
//響應(yīng)攔截器
instance.interceptors.response.use(function(response) {
if(response.status == 500) {
alert("服務(wù)器內(nèi)部故障");
}
return response
});
好啦,以上就是簡(jiǎn)單的學(xué)習(xí),簡(jiǎn)單了解一下,axios的強(qiáng)大之處~文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-783042.html
后面周末會(huì)做一個(gè)簡(jiǎn)單小項(xiàng)目練練手,到時(shí)候再和大家分享分享~文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-783042.html
到了這里,關(guān)于Axios基本使用,為學(xué)習(xí)后續(xù)的Vue服務(wù)【發(fā)送請(qǐng)求+并發(fā)請(qǐng)求+前端攔截器】的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!