[Axios]Axios快速入门
1.什么是Axios
Axios是基于promise的用于浏览器和nodejs的HTTP客户端的一个中间件。
他可以实现从浏览器中创建XMLHttpRequest;从nodejs发出http请求;支持promiseAPI;拦截 请求和响应;转换请求和响应数据;取消请求;自动转换JSON数据;客户端支持防止CSRF/XSRF攻击等功能。
2.准备工作
json-server
我们使用json-server这个模拟服务端接口数据的工具辅助测试,json-server就是一个存储了json格式的数据的一个本地模拟服务器。
npm install -g json-server
安装后我们在项目文件夹下创建一个db.json,用来存储我们要模拟的json格式的数据。
{
"posts": [
{
"id": 1,
"title": "长江七号",
"author": "周星驰"
},
{
"id": 2,
"title": "c programming",
"author": "tl"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
},
{
"body": "测试二号",
"postId": 2,
"id": 2
}
],
"profile": {
"name": "typicode"
}
}
可以运行以下指令来开启一个虚假的服务器。
json-server --watch db.json
axios的引入
安装
npm install axios
使用script引入
3.Axios的基本使用
3.1 前端实现
我们写一个简单的html网页,用于测试。
定义四个按钮,分别用来发送不同类型的请求。
首先获取按钮,之后我们为按钮绑定方法,这里的方法使用axios实现。
Document
基本使用
3.2 API传入参数方式创建请求
可以看到,axios的API基本实现需要指定几个参数,
axios({
method:'GET', //指定使用的方法
// 配置url 这里如果是delete等方法需要传入指定参数
url:'http://localhost:3000/posts/3',
}).then(response =>{
console.log(response);
});
如有必要,可以设置传入的数据。
axios({
method:'POST',
url:'http://localhost:3000/posts',
//设置请求体
data:{
title:"今天天气不错",
author:"张三"
}
}).then(response =>{
console.log(response);
});
3.3 直接执行请求
也可以让axios直接指定命令,执行请求
// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 可选地,上面的请求可以这样做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
3.4 设定Axios默认配置
axios.defaults.method = 'GET'; //设置默认请求类型为GET
//设置url为'http://localhost:3000'
axios.defaults.baseURL = 'http://localhost:3000';
axios.defaults.params = {id:100}; //默认传入参数id:100
axios.defaults.timeout = 3000;
3.5 创建实例对象
可以通过实例对象的创建来实现一个Axios操作,这里定义了两个对象,通过get方法进行使用。
//发送GET请求
const btns = document.querySelectorAll('button');
//创建实例对象
const duanzi = axios.create({
baseURL:'https://api.apiopen.top',
timeout:3000
});
//这里duanzi与axios对象的功能几乎是一样的
const another = axios.create({
baseURL:'https://b.com',
timeout:3000
});
console.log(duanzi)
duanzi({
url:'/getJoke'
}).then(response =>{
console.log(response);
})
duanzi.get('/getJoke').then(response =>{
console.log(response.data)
})
4.拦截器和错误处理
拦截器可以在发出请求或响应请求之前进行一些操作。
这里给出两个例子。
// 设置请求拦截器
axios.interceptors.request.use(function (config) {
// Do something before request is sent
console.log('请求拦截器 成功')
// throw '参数出了问题'
return config;
}, function (error) {
// Do something with request error
console.log('请求拦截器 失败')
return Promise.reject(error);
});
// 设置响应拦截器
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
console.log('响应拦截器 成功')
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
console.log('响应拦截器 失败')
return Promise.reject(error);
});
//发送请求
axios({
method:'GET',
url:'http://localhost:3000/posts'
}).then(response =>{
console.log(response)
}).catch(response =>{
console.log('回调失败')
})
运行后,可以得到
如果我们在请求拦截器中throw一个错误,那么会发生
5.取消请求
我们可以在请求发出后对请求进行取消,首先设置json-server一个延迟,方便我们取消。
json-server --watch db.json -d 2000
给出一个取消案例。
取消请求
使用
cancelToken: new axios.CancelToken(function (c) {})
这样一个参数,去配置取消的操作。