進(jìn)入項目安裝axios(npm install axios -S)
axios配置
項目中安裝axios模塊完成后,進(jìn)行以下配置:
main.js
//引入axios
import Axios from 'axios'
//修改原型鏈,全局使用axios,這樣之后可在每個組件的methods中調(diào)用$axios命令完成數(shù)據(jù)請求
Vue.prototype.$axios=Axios
get請求
methods:{
getData(){
this.$axios.get('https://www.apiopen.top/journalismApi')
.then(res=>{
console.log(res)//返回請求的結(jié)果
})
.catch(err=>{
console.log(err)
})
}
}
}
post請求
axios.post('/user',{
firstName:'Fred',
lastName:'Flintstone'
})
.then(function(res){
console.log(res);
})
.catch(function(err){
console.log(err);
});
Axios攔截器配置
main.js
//定義一個請求攔截器
Axios.interceptors.request.use(function(config){
console.log('Axios.interceptors.request') //在請求發(fā)出之前進(jìn)行一些操作
return config
})
//定義一個響應(yīng)攔截器
Axios.interceptors.response.use(function(config){
console.log('Axios.interceptors.response')//在這里對返回的數(shù)據(jù)進(jìn)行處理
return config
})