axios學習
阿新 • • 發佈:2020-08-02
get
created(){
axios('/test.json').then((res)=>{
window.console.log(res)
})
}
axios請求方法:
- get 獲取資料
- post 提交資料(表單提交、檔案上傳)
- delete 刪除資料
- patch 更新資料 (只是將修改資料到後端)
- put 更新資料 (所有資料推送到後端)
第二種寫法
axios({ method:'get', url:'/test.json', params:{ id:12 } }).then(res=>{ console.log(res) })
created(){
axios('/test.json',{
params:{
id:12
}
}).then((res)=>{
window.console.log(res)
})
}
post
兩種書寫方式 axios.post('/post',data).then((res)=>{ window.console.log(res) }) axios.post({ methods:'post', url:'/post', data:data }).then((res)=>{ window.console.log(res) })
put和patch
let data = {
id:12
}
axios.put('/put',data).then((res)=>{
window.console.log(res);
})
axios.patch('/patch',data).then((res)=>{
window.console.log(res);
})
delete
axios.delete('/delete',{ params:{ id:12 } }).then(res=>{ window.console.log(res); })
併發請求
axios.all() axios.spread()
axios.all([
axios.get('/data.json'),
axios.get('/test.json'),
]).then(
axios.spread((dataRes,testRes)=>{
window.console.log(dataRes,testRes);
})
)
axios建立例項
let instance = axios.create({
baseURL:'http://localhost:8080',
timeout:1000
})
let axios2 = axios.create({
baseURL:'http://localhost:9090',
timeout:5000
})
instance.get('/data.json').then(res=>{
window.console.log(res)
})
axios2.get('/test.json').then(res=>{
window.console.log(res)
})
axios基本配置
axios.create({
baseURL:'地址',//請求域名
timeout:1000, //請求時長ms
url:'data.json' //請求路徑
method:'get' //請求方式
headers:{
token:''
}, //設定請求頭
params:{}, //請求拼接
data:{}, //請求引數在請求體
})
axios2.get('/test.json').then(res=>{
window.console.log(res)
})
axios全域性配置
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios請求配置
axios請求配置
攔截器
在響應或者請求的時候被處理前攔截它
請求攔截器
//請求攔截
axios.interceptors.request.use(config=>{
//再發送請求前做些什麼
return config
},err=>{
//請求錯誤的時候做些什麼
return Promise.reject(err)
})
//響應攔截器
axios.interceptors.use(res=>{
//請求成功對響應資料做處理
return res
},err=>{
//響應錯誤做些什麼
return Promise.reject(err)
})
取消攔截器
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
舉例
//登陸狀態
let instance = axios.create({})
instance.interceptors.request.use(
config=>{
config.headers.token = ''
return config
}
)
//不需要登陸介面
let newInstance = axios.create({})
//移動端開發
let instance_phone = axios.create({})
instance_phone.interceptors.request.use(config=>{
$('modal').show()
return config
})
instance_phone.interceptors.response.use(
res=>{
$('modal').hide()
return res
}
)