axios的基本用法
axios是一个第三方库文件,具有以下特征:
(1)支持浏览器和node
(2)支持Promise
(3)能拦截请求和响应
(4)自动转换JSON数据
1、axios的基本用法
axios.get('http://localhost:3000/adata').then(function(res) {
console.log(res.data); //data获取后台响应数据,res是一个对象
})
2、axios传递参数
(1)get三种方式
axios.get('http://localhost:3000/axios?id=123').then(function(res) {
console.log(res.data);
});
axios.get('http://localhost:3000/axios/123').then(function(res) {
console.log(res.data);
});
axios.get('http://localhost:3000/axios', {
params: {
id: 234
}
}).then(function(res) {
console.log(res.data);
});
(2)delete三种方式
axios.delete('http://localhost:3000/axios?id=123').then(function(res) {
console.log(res.data);
});
axios.delete('http://localhost:3000/axios/123').then(function(res) {
console.log(res.data);
});
axios.delete('http://localhost:3000/axios', {
params: {
id: 234
}
}).then(function(res) {
console.log(res.data);
});
(3)post的两种方式
axios.post('http://localhost:3000/axios', {
uname: 'kun',
pwd: 123
}).then(function(res) {
console.log(res.data);
})
// ----------------------------------------------------------------
var params = new URLSearchParams();
params.append('uname', 'ikun');
params.append('pwd', '111');
axios.post('http://localhost:3000/axios', params).then(function(res) {
console.log(res.data);
})
(4)put的两种方式
axios.put('http://localhost:3000/axios/123', {
uname: 'ikun',
pwd: 222
}).then(function(res) {
console.log(res.data);
})
var params = new URLSearchParams();
params.append('uname', 'kun');
params.append('pwd', '222');
axios.put('http://localhost:3000/axios', params).then(function(res) {
console.log(res.data);
})
3、axios的响应结果
主要属性
data: 实际响应回来的数据
header: 响应头信息
status: 响应状态码
statusText: 响应状态信息
4、axios的全局配置
axios.defaults.timeout = 3000; // 超时时间
axios.defaults.baseURL = 'http://localhost:3000'; // 默认地址
axios.defaults.headers['mytoken'] = 'kun&ikun'; // 设置请求头

浙公网安备 33010602011771号