2.axios的基本使用,获取增删改,常用配置项和axios.create,请求拦截器和响应拦截器,取消请求和axios.all批量发送请求

一:axios的基本使用,获取增删改

        1.axios调用的返回值是Promise实例。

        2.成功的值叫response,失败的值叫error。

        3.axios成功的值是一个axios封装的response对象,服务器返回的真正数据在response.data中

        4.携带query参数时,编写的配置项叫做params

        5.携带params参数时,就需要自己手动拼在url中,如下按钮5

<script src="./js/axios.min.js"></script>
<body>
<button id="btn1">点我获取所有人的信息</button>
<br>
<button id="btn2">点我获取某个人的信息</button>
<input id="person_id" type="text" placeholder="请输入一个人的id">
<br>
<button id="btn3">点我添加某个人的信息</button>
<input id="person_name" type="text" placeholder="请输入一个人的姓名">
<input id="person_age" type="text" placeholder="请输入一个人的年龄">
<br>
<button id="btn4">点我更新某个人的信息</button>
<input id="person_updata_id" type="text" placeholder="请输入要修改的id号">
<input id="person_updata_name" type="text" placeholder="请输入更新后的名字">
<input id="person_updata_age" type="text" placeholder="请输入更新后的年龄">
<br>
<button id="btn5">删除某人信息</button>
<input id="person_dele_id" type="text" placeholder="请输入要删除的id">

<script>
    const btn1 = document.getElementById('btn1')
    const btn2 = document.getElementById('btn2')
    const personId = document.getElementById('person_id')
    const btn3 = document.getElementById('btn3')
    const personName = document.getElementById('person_name')
    const personAge = document.getElementById('person_age')
    const personUpdataId = document.getElementById('person_updata_id')
    const personUpdataName = document.getElementById('person_updata_name')
    const personUpdataAge = document.getElementById('person_updata_age')
    const btn5 = document.getElementById('btn5')
    const personDeleId = document.getElementById('person_dele_id')
    // 1.获取所有人信息 --发送GET请求--  不携带参数
    btn1.onclick = async()=>{
        // 完整版
        axios({
            url:'http://localhost:5000/persons',   //请求地址
            method:'GET'     //请求方式
        }).then(
            // 学Promise时then里面的参数是value和reason,axios官方文档是 以下两个
            response => console.log('请求成功',response.data),
            error => console.log('请求失败',error)
        )
         
        // // 精简版   不能配置更多的属性
        // axios.get('http://localhost:5000/persons').then(
        //     response => console.log('请求成功',response.data),
        //     error => console.log('请求失败',error)
        // )

        // // 更精简版  只等待成功结果的版本 用 async 和 await
        // const res = await axios.get('http://localhost:5000/persons')
        // console.log(res.data)
    }

    // 2.获取某个人的信息 --发送GET请求-- 携带query参数  
    btn2.onclick = ()=>{
        // // 完整版
        // axios({
        //     url:'http://localhost:5000/person',
        //     method:'GET',
        //     params:{id:personId.value}   //此处写的是params,但携带的是query参数
        // }).then(
        //     response => {console.log('成功',response.data )},
        //     error => {console.log('失败',error)}
        // )

         // 精简版            带params
         axios.get('http://localhost:5000/person',{params:{id:personId.value}}).then(
             response => {console.log('成功',response.data)},
             error =>{console.log('失败')}
         )

    }

    // 3.添加某个人的信息 --发送POST请求-- 携带json编码参数 或 urlencoded编码   
    btn3.onclick = ()=>{
        // // 完整版
        // axios({
        //     url:'http://localhost:5000/person',
        //     method:'POST',
        //     data:{name:personName.value,age:personAge.value}
        // }).then(
        //     response => console.log('成功',response.data),
        //     error => console.log('失败',error)
        // )

        //精简版             不带data,直接写参数对象
        axios.post('http://localhost:5000/person',{name:personName.value,age:personAge.value}).then(
           response => console.log('成功',response.data),
           error => console.log('失败',error)
        )

    } 

    // 4.更新某个人的信息 --发送PUT请求-- 携带json编码参数 或 urlencoded编码
    btn4.onclick = () =>{
        // // 完整版
        // axios({
        //     url:'http://localhost:5000/person',
        //     method:'PUT',
        //     data:{id:personUpdataId.value,
        //           name:personUpdataName.value,
        //           age:personUpdataAge.value}
        // }).then(
        //     response => console.log('成功',response.data),
        //     error => console.log('失败')

        // )
        // 精简版
        axios.put('http://localhost:5000/person',{id:personUpdataId.value,name:personUpdataName.value,age:personUpdataAge.value}).then(
            response => console.log('成功',response.data),
            error => console.log('失败')  
        )
    }

    // 5.删除某个人的信息 --发送DELETE请求-- params参数没有对应的axios内置对象,我们要用模板字符串
    btn5.onclick = () =>{
        axios({
            url:`http://localhost:5000/person/${personDeleId.value}`,
            method:'DELETE',
            // params:{id:personDeleId.value}  这是错误的写法。。。不应该用params
        }).then(
            response => console.log('成功',response.data),
            error => console.log('失败')
        )
    }
</script>
</body>

二:axios常用配置项和axios.create

                axios.create(config)

                        1. 根据指定配置创建一个新的axios, 也就是每个新axios都有自己的配置

                        2. 新axios只是没有取消请求和批量发请求的方法, 其它所有语法都是一致的

                        3. 为什么要设计这个语法?

                                需求: 项目中有部分接口需要的配置与另一部分接口需要的配置不太一样

 

	<body>
		<button id="btn">点我获取所有人</button><br/><br/>
		<button id="btn2">点我获取测试数据</button><br/><br/>
		<button id="btn3">点我获取笑话信息</button><br/><br/>

        
		<script type="text/javascript" >
			const btn = document.getElementById('btn')
			const btn2 = document.getElementById('btn2')
			const btn3 = document.getElementById('btn3')

            const axios2 = axios.create({
                timeout : 3000,
                // headers : {name:'yang'},   这台服务器不允许修改请求头headers,不是我代码的锅
                baseURL : 'https://api.apiopen.top'
            })

            //给axios配置默认属性 , 所有方法的超时时间都设置为2秒,请求头都是atguigu,请求的url通用路径
			axios.defaults.timeout = 2000
			axios.defaults.headers = {school:'atguigu'}
			axios.defaults.baseURL = 'http://localhost:5000'
            
            btn.onclick = ()=>{
				axios({
					url:'/persons', //请求地址
					method:'GET',//请求方式
					//params:{delay:3000},//配置query参数
					//data:{c:3,d:3},//配置请求体参数(json编码)
					//data:'e=5&f=6',//配置请求体参数(urlencoded编码)
					//timeout:2000,//配置超时时间
					//headers:{school:'atguigu'} //配置请求头
					//responseType:'json'//配置响应数据的格式(默认值)
				}).then(
					response => {console.log('成功了',response.data);},
					error => {console.log('失败了',error);}
				)
			}
		
			btn2.onclick = ()=>{
				axios({
					url:'/test1', //请求地址
					method:'GET',//请求方式
					//timeout:2000,//配置超时时间
					//headers:{school:'atguigu'} //配置请求头
				}).then(
					response => {console.log('成功了',response.data);},
					error => {console.log('失败了',error);}
				)
			}
			
            // 上面我们统一设置了 url 的开头为 'http://localhost:5000'
            // 但是我们下面的这个方法 url开头和默认设置的并不相同 ,此时用 axios.create方法重新创建一个axios2
            // 要配置在初始 axios 前面 
			btn3.onclick = ()=>{
				axios2({
					url:'/getJoke',
                    method:'GET'
				}).then(
                    response => {console.log('成功了',response.data);},
					error => {console.log('失败了',error);}
                )
			}
		</script>
	</body>

三:axios中的请求拦截器和响应拦截器

                axios请求拦截器

                    1.是什么?       在真正发请求前执行的一个回调函数

                    2.作用:     对所有的请求做统一的处理:追加请求头、追加参数、界面loading提示等等

               

                axios响应拦截器

                    1.是什么?        得到响应之后执行的一组回调函数

                    2.作用:

                            若请求成功,对成功的数据进行处理

                            若请求失败,对失败进行统一的操作

	<body>
		<button id="btn">点我获取所有人</button><br/><br/>
		<script type="text/javascript" >
			const btn = document.getElementById('btn')

			//请求拦截器
			axios.interceptors.request.use((config)=>{
				console.log('请求拦截器1执行了');
				if(Date.now() % 2 === 0){   
                    //如果当前时间戳整除2,
					config.headers.token = 'atguigu'
				}
				return config
			})

			//响应拦截器
			axios.interceptors.response.use(
				response => {
					console.log('响应拦截器成功的回调执行了',response);
					if(Date.now() % 2 === 0) return response.data
					else return '时间戳不是偶数,不能给你数据'
				},
				error => {
					console.log('响应拦截器失败的回调执行了');
					alert(error);   //弹出出错信息
					return new Promise(()=>{})   //中断promise链
				}
			)
			
            // 只要成功的结果,不成功也会有提示。因为在上面的响应拦截器里面写了
			btn.onclick = async()=>{
				const result = await axios.get('http://localhost:5000/persons21')
				console.log(result);
			}
		</script>
	</body>

四:axios中取消请求

五:axios.all批量发送请求

	<body>
		<button id="btn">点我批量发送请求</button><br/><br/>
		<script type="text/javascript" >
			const btn = document.getElementById('btn')

			btn.onclick = async()=>{
				axios.all([
					axios.get('http://localhost:5000/test1'),
					axios.get('http://localhost:5000/test2?delay=3000'),
					axios.get('http://localhost:5000/test3'),
				]).then(
					response => {console.log(response);},
					error => {console.log(error);}
				)
			}
		</script>
	</body>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值