什么是axios?
axios使用一个基于promise的http库网络插件,可以在浏览器和node.js中使用。
支持promise API,自动装换JSON数据
安装:
npm install axios
导入:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
使用:
//发送get请求
axios.get('地址?id=user')//括号内为地址和参数
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
//上面的代码还可以把参数单独出来
axios.get('地址', {
params: {
id: user
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
//发送post请求
axios.post('地址', {
key: 'value',//这个为发送post的参数
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
响应请求的结构
{
// `data` 由服务器提供的响应
data: {},
// `status` 来自服务器响应的 HTTP 状态码
status: 200,
// `statusText` 来自服务器响应的 HTTP 状态信息
statusText: 'OK',
// `headers` 服务器响应头
headers: {},
// `config` 是为请求提供的配置信息
config: {}
}
//获取响应的内容
axios.get('地址')
.then(function(response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
配置默认值
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//默认请求类型
axios.defaults.timeout = 2500;
//默认超时时间
axios.defaults.baseURL="http://127.0.0.1";
//默认根地址,有了默认根地址后,后面在发送请求不用写跟地址,项目上线后可以修改默认根地址
错误处理
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});