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
}
)