axios学习

一、了解axios

1. axios 是什么

axios 是基于Promise 的HTTP客户端,可以在浏览器和node 环境中运行;

在浏览器中发送ajax请求,在node 中发送http请求

特点

  • 在浏览器端发送ajax请求
  • 在node中发送http请求
  • 支持promise api
  • 请求响应拦截器
  • 传输请求、响应体数据
  • 取消请求
  • ...

安装方式

学习阶段用后两种(在bootCDN 中搜索)

2. axios 请求方法

2.1 基本使用--通用型

javascript 复制代码
axios({
                method: 'GET',
                url: 'http://localhost:3000/posts/1',
                headers: {
                    name: 'hello'
                },
                data: {
                    msg: 'hi'
                }
            }).then(response => {
                console.log(response);
            })

2.2 请求方法

  • axios.request(config) axios.request(配置)
  • axios.get(url[, config]) axios.get(url[, config])
  • axios.delete(url[, config]) axios.delete(url[, 配置])
  • axios.head(url[, config]) axios.head(url[, 配置])
  • axios.options(url[, config]) axios.options(url[, config])
  • axios.post(url[, data[, config]])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]]) axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])
  • axios.patch(url[, data[, config]])
javascript 复制代码
 btns[1].onclick = () => {
            axios.post('http://localhost:3000/comments', {
                title: 'hi',
                name: 'hello'
            }, {
                // 查询字符串
                params: {
                    p: 100
                },
                query: {
                    b: 200
                },
                headers: {
                    c: 300
                }
            })
        }

3. axios 请求响应结果结构介绍

  • config:请求url,请求方法,请求头...
  • data:响应体结果,axios自动将响应结果转换成json 格式
  • headers:响应头
  • request:原生ajax请求,也就是XMLHttpRequest实例对象

4. axios 配置对象介绍

axios 请求对象配置信息可以在下面网址中进行查看。
https://github.com/axios/axios/blob/v1.x/README.md#axiosrequestconfig

axios 默认配置:

javascript 复制代码
 const btns = document.querySelectorAll('button');
        axios.defaults.baseURL = 'http://localhost:3000';
        axios.defaults.headers = {name:'hello'};
        axios.defaults.params={msg:'hi'}
        btns[1].onclick = () => {
            axios.post('http://localhost:3000/comments', {
                title: 'hi',
                name: 'hello'
            }, {
                query: {
                    b: 200
                },
            })
        }

5. 创建axios 实例对象

javascript 复制代码
const btns = document.querySelectorAll('button');
        // 创建axios 实例对象
        const test = axios.create({
            baseURL: 'http://localhost:3000',
            timeout: 2000
        })
        // test和axios 的功能几近一样
        test({
            url: '/test'
        }).then(res => {
            console.log(res);
        })

        test.get('/test').then(res => {
            console.log(res.data);
        })

实例对象的好处:

当需要同时向两个或多个服务器端口发送请求,就可以创建多个实例对象进行数据请求。

javascript 复制代码
const test1 = axios.create({
            baseURL: 'http://localhost:3000',
            timeout: 2000
        })
        const test2 = axios.create({
            baseURL: 'http://localhost:8000',
            timeout: 2000
        })

6. 拦截器

一般情况下,如果请求拦截器抛出了错误,那么接下来就会执行相应拦截器的错误回调,再接着执行请求的错误回调。

javascript 复制代码
		// 请求拦截器
        axios.interceptors.request.use(config => {
            console.log('请求拦截器成功 1号');
            return config
        },err => {
            console.log('请求拦截器失败 1号');
            return Promise.reject(err)
        })
		// 响应拦截器
        axios.interceptors.response.use(response => {
            console.log('响应拦截器成功 1号');
            return response
        },err => {
            console.log('响应拦截器失败 1号');
            return Promise.reject(err)
        })

        axios({
            method: 'GET',
            url: 'http://localhost:3000/posts'
        }).then(response => {
            console.log(response.data);
        })

拦截器的成功回调中形参是请求体或者响应体,拦截器中也可以对请求体或者响应体进行修改。

javascript 复制代码
 axios.interceptors.request.use(config => {
            console.log('请求拦截器成功 1号');
            // config 指的是请求体 拦截其中也可以对请求体做修改
            config.params={
                name:'hi',
                msg:'hello'
            }
            return config
        },err => {
            console.log('请求拦截器失败 1号');
            return Promise.reject(err)
        })

        axios.interceptors.response.use(response => {
            console.log('响应拦截器成功 1号');
            return response.data
        },err => {
            console.log('响应拦截器失败 1号');
            return Promise.reject(err)
        })

7. axios 取消请求

javascript 复制代码
const btns = document.querySelectorAll('button')
        let isSending = false
        const controller = new AbortController();
        btns[0].onclick = () => {
            if (isSending) {
                controller.abort()
            }
            isSending = true
            axios({
                method: 'GET',
                url: 'http://localhost:3000/posts',
                signal: controller.signal,
                data: {
                    msg: '响应体数据'
                }
            }).then(res => {
                isSending = false
                console.log(res.data);
            }).catch(err => {
                console.log(err);
            })
        }

        btns[1].onclick = () => {
            controller.abort()
        }

二、源码分析

1. 源码介绍

https://github.com/axios/axios

2. axios与Axios 关系

  1. 从语法上来说:axios不是Axios的实例

    axios 并不是newAxios 创建出来的,也就不是Axios的实例
  2. 从功能上来说:axios是Axios的实例
    但是axios通过扩展添加了Axios 的功能,也可以说是Axios的实例
  3. axios是Axios.prototype.request函数bind0返回的函数
  4. axios作为对象有Axios原型对象上的所有方法,有Axios对象上所有属性

3. instance 和axios 区别

  1. 相同:
    (1) 都是一个能发任意请求的函数:request(config)
    (2) 都有发特定请求的各种方法:get()/post()/put()/delete()
    (3) 都有默认配置和拦截器的属性:defaults/interceptors
  2. 不同:
    (1) 默认配置很可能不一样
    (2) instance没有axios后面添加的一些方法:create()/CancelToken()/all()

4. 请求/响应拦截器

  1. 请求拦截器
  • 是在真正发送请求前执行的回调函数
  • 可以对请求进行检查或配置进行特定处理
  • 成功的回调函数,传递的默认是config(也必须是)
  • 失败的回调函数,传递的默认是error
  1. 响应拦截器
  • 在请求得到响应后执行的回调函数
  • 可以对响应数据进行特定处理
  • 成功的回调函数,传递的默认是response
  • 失败的回调函数,传递的默认是error

5. axios的请求/响应数据转换器

  1. 请求转换器:对请求头和请求体数据进行特定处理的函数
javascript 复制代码
if(utils.isObject(data)){
setContentTypelfUnset(headers,'application/json;charset=utf-8');
return JSON.stringify(data);
}
  1. 响应转换器:将响应体json字符串解析为js对象或数组的函数
javascript 复制代码
response.data JSON.parse(response.data)
相关推荐
知识分享小能手1 天前
React学习教程,从入门到精通, React 属性(Props)语法知识点与案例详解(14)
前端·javascript·vue.js·学习·react.js·vue·react
茯苓gao1 天前
STM32G4 速度环开环,电流环闭环 IF模式建模
笔记·stm32·单片机·嵌入式硬件·学习
是誰萆微了承諾1 天前
【golang学习笔记 gin 】1.2 redis 的使用
笔记·学习·golang
DKPT1 天前
Java内存区域与内存溢出
java·开发语言·jvm·笔记·学习
aaaweiaaaaaa1 天前
HTML和CSS学习
前端·css·学习·html
看海天一色听风起雨落1 天前
Python学习之装饰器
开发语言·python·学习
speop1 天前
llm的一点学习笔记
笔记·学习
非凡ghost1 天前
FxSound:提升音频体验,让音乐更动听
前端·学习·音视频·生活·软件需求
ue星空1 天前
月2期学习笔记
学习·游戏·ue5
萧邀人1 天前
第二课、熟悉Cocos Creator 编辑器界面
学习