支持浏览器和 node.js
支持 promise
能拦截请求和响应
自动转换 JSON 数据
1. axios基本用法
axios.get(‘/adata')
.then(ret=>{
// data属性名称是固定的,用于获取后台响应的数据
console.log(ret.data)
})
2.get : 查询数据
- 通过url传递参数
axios.get(‘/adata?id=123')
.then(ret=>{
console.log(ret.data)
})
2.通过params选项传递参数
axios.get(‘/adata/123')
.then(ret=>{
console.log(ret.data)
})
axios.get(‘/adata‘,{
params: {
id: 123
}
})
.then(ret=>{
console.log(ret.data)
})
3.post : 添加数据
通过选项传递参数(默认传递的是 json 格式的数据
axios.post(‘/adata',{
uname: 'tom',
pwd: 123
}).then(ret=>{
console.log(ret.data)
})
通过 URLSearchParams 传递参数(application/x-www-form-urlencoded)
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/api/test', params).then(ret=>{
console.log(ret.data)
})
4.put : 修改数据
传递参数与post相似
axios.put(‘/adata/123',{
uname: 'tom',
pwd: 123
}).then(ret=>{
console.log(ret.data)
})
5.delete :删除数据
- 通过url传递参数
axios.delete(‘/adata?id=123')
.then(ret=>{
console.log(ret.data)
})
2.通过params传递参数
axios.delete(‘/adata/123')
.then(ret=>{
console.log(ret.data)
})
axios.delete(‘/adata‘,{
params: {
id: 123
}
})
.then(ret=>{
console.log(ret.data)
})
6.axios的全局配置
axios.defaults.timeout = 3000; // 超时时间
axios.defaults.baseURL = 'http://localhost:3000/app'; // 默认地址
axios.defaults.headers[‘mytoken’] = ‘aqwerwqwerqwer2ewrwe23eresdf23’// 设置请求头
7.axios请求拦截器
在请求发出之前对数据做一些加工处理
//添加一个请求拦截器
axios.interceptors.request.use(function(config){
//在请求发出之前进行一些信息设置
return config;
},function(err){
// 处理响应的错误信息
});
8.axios响应拦截器
/添加一个响应拦截器
axios.interceptors.response.use(function(res){
//在这里对返回的数据进行处理
return res;
},function(err){
// 处理响应的错误信息
})