一.axios的作用
1.支持浏览器和 node.js
2.支持 promise
3.能拦截请求和响应
4.自动转换 JSON 数据
二.axios基本用法
axios.get(‘/adata')
.then(ret=>{
// data属性名称是固定的,用于获取后台响应的数据
console.log(ret.data)
})
三.get : 查询数据
通过url传递参数
axios.get(‘/adata?id=123')
.then(ret=>{
console.log(ret.data)
})
axios.get(‘/adata‘,{
params: {
id: 123
}
})
.then(ret=>{
console.log(ret.data)
})
四.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)
})
五.axios的全局配置
axios.defaults.timeout = 3000; // 超时时间
axios.defaults.baseURL = 'http://localhost:3000/app'; // 默认地址
axios.defaults.headers[‘mytoken’] = ‘aqwerwqwerqwer2ewrwe23eresdf23’// 设置请求头
六.axios请求拦截器
在请求发出之前对数据做一些加工处理
//添加一个请求拦截器
axios.interceptors.request.use(function(config){
//在请求发出之前进行一些信息设置
return config;
},function(err){
// 处理响应的错误信息
});
七.axios响应拦截器
添加一个响应拦截器
axios.interceptors.response.use(function(res){
//在这里对返回的数据进行处理
return res;
},function(err){
// 处理响应的错误信息
})