axios
axios是什么
- Axios是基于promise和HTTP库,可以用在浏览器和nodejs中,目前前端最流行的ajax请求库
- react.vue官方都推荐使用axios发ajax请求
axios特点
- 可以在浏览器端发送ajax请求
- 可以在nodejs中发送http请求
- 支持promise相关操作
- 请求响应拦截器
- 可以对请求数据进行转换
- 可以取消请求
- 自动将结果转为JSON数据
- 还可以阻挡XSRF攻击
axios常用语法
-
axios(config): 通用/最本质的发任意类型请求的方式
-
axios(url[, config]): 可以只指定 url 发 get 请求
-
axios.request(config): 等同于 axios(config)
-
axios.get(url[, config]): 发 get 请求
-
axios.delete(url[, config]): 发 delete 请求
-
axios.post(url[, data, config]): 发 post 请求
-
axios.put(url[, data, config]): 发 put 请求
-
axios.defaults.xxx: 请求的默认全局配置
-
axios.interceptors.request.use(): 添加请求拦截器
-
axios.interceptors.response.use(): 添加响应拦截器
-
axios.Cancel(): 用于创建取消请求的错误对象
-
axios.CancelToken(): 用于创建取消请求的 token 对象
-
axios.isCancel(): 是否是一个取消请求的错误
-
axios.all(promises): 用于批量执行多个异步请求
-
axios.spread(): 用来指定接收所有成功数据的回调函数的方法
-
axios.create([config]): 创建一个新的 axios(它没有下面的功能
axios请求响应结果的结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ERxBrzTK-1651020732030)(C:\Users\23937\AppData\Roaming\Typora\typora-user-images\image-20220426230142025.png)]
- config : 配置对象包含请求类型,url,请求体等数据
- data : 响应体的内容,服务器返回结果,axios自动将其转换为JSON
- headers : 响应头信息
- request : 原生的AJAX请求对象,XMLHttpRequest实例对象
- status : 响应状态码
- statusText : 响应字符串
axios配置对象
{
// `url` 指明给谁发送请求
url: '/user',
// `method` 设置请求的类型
method: 'get', // default
// `baseURL` 设定url的基础结构
// axios使用时自动将baseURL和url结合
baseURL: 'https://some-domain.com/api/',
// `transformRequest` 对请求进行处理并返回服务器
transformRequest: [function (data, headers) {
// Do whatever you want to transform the data
return data;
}],
// `transformResponse` 对相应的结果进行改变
transformResponse: [function (data) {
// Do whatever you want to transform the data
return data;
}],
// `headers` 配置请求头信息
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` 设定url参数
params: {
ID: 12345
},
// `paramsSerializer`参数序列化
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// `data` 被发送的数据
data: {
firstName: 'Fred'
},
// syntax alternative to send data into the body
// method post
// only the value is sent, not the key
data: 'Country=Brasil&City=Belo Horizonte',
// `timeout` 请求超时的毫秒数
timeout: 1000, // default is `0` (no timeout)
// `withCredentials` 跨域请求时是否需要凭证 对Cookie设置
withCredentials: false, // default
// `adapter` 请求适配器设置
adapter: function (config) {
/* ... */
},
// `auth` 请求验证
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` 请求响应体数据的格式
responseType: 'json', // default
// `responseEncoding` 响应数据的编码
responseEncoding: 'utf8', // default
// `xsrfCookieName` 跨域请求表示
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` 头信息设置
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress` 上传回调
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `onDownloadProgress` 下载回调
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// `maxContentLength` 响应http响应体的最大尺寸
maxContentLength: 2000,
// `maxBodyLength` 请求体的最大内容
maxBodyLength: 2000,
// `validateStatus` 响应结果成功规则 进行设置
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects` 最大跳转次数
maxRedirects: 21, // default
// `beforeRedirect`
beforeRedirect: (options, { headers }) => {
if (options.hostname === "example.com") {
options.auth = "user:password";
}
};
// `socketPath` 数据转发
socketPath: null, // default
// `httpAgent` and `httpsAgent`
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// `proxy` 设置代理
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` ajax请求取消设置
cancelToken: new CancelToken(function (cancel) {
}),
}
axios默认配置
//举几个例子
axios,defaults.method = 'GET' //设置默认请求类型为GET
axios.defaults.baseURL = 'htttp://localhost:3000' //设置基础URL
同样的在整个axios配置对象都能设置默认对象
axios创建实例对象并发送请求
用 axios.create 创建对象
const Menu = axios.create({
baseURL: 'https://XXX.com',
timeout: 2000
})
Menu({
url : 'XXX'
}).then(res =>{
//成功的回调函数
})
axios拦截器
- 请求拦截器: 对请求数据进行判断处理
- 响应拦截器 : 对响应数据进行处理
// 设置一个请求拦截器
axios.interceptors.request.use(function (config) {
console.log('请求拦截器 成功')
return config;
}, function (error) {
console.log('请求拦截器 失败')
return Promis.reject(error)
});
// 设置一个响应拦截器
axios.interceptors.response.use(function (response) {
console.log('响应拦截器 成功')
return response;
}, function (error) {
console.log('响应拦截器 失败')
return Promise.reject(error);
});
//发送请求
axios({
method:'GET',
url;''
}).then(res =>{
console.log(自定义回调成功)
}),catch(res => {
console.log(自定义回调失败)
})
// 先走请求拦截器回调 然后走响应拦截器回调 最后走自定义回调函数
axios取消请求
//声明全局变量
cancel = null;
//给一个按钮绑定事件
btns[0].onclick = function(){
axios({
method : 'GET',
url :'XXXXX'
//1.添加配置对象的属性
cancelToken: new axios.CancelToken(function(c){
cancel = c;
}).then(res => {
console.log(res)
})
})
}
//另一个按钮绑定取消事件
btn[1].onclick = function() {
cancel();
}
如何在另一个请求完成前取消任何请求?
//声明全局变量
cancel = null;
//给一个按钮绑定事件
btns[0].onclick = function(){
//检测上一次的请求是否完成
if(cancel !== null) {
cancel();
}
axios({
method : 'GET',
url :'XXXXX'
//1.添加配置对象的属性
cancelToken: new axios.CancelToken(function(c){
cancel = c;
}).then(res => {
console.log(res)
//将cancel初始化
cancel = null
})
})
}
//另一个按钮绑定取消事件
btn[1].onclick = function() {
cancel();
}