Axios的使用方式,前后端分离通信必不可少的技术

axios

一、接口文档

接口名请求方式请求参数请求地址
获取所有球星get无参href
获得所有球星post无参href
根据id获取学生getid stringhref
根据名字获取学生postname stringhref

该接口文档中,后两个接口是模拟老师的,需要有后端操作,前两个后端数据可以用mockjs进行模拟

一、axios

axios是基于promiseajax的一种封装

ajax mvc

axios mvvm

可以使用mockjs对后端数据进行模拟实践,创建一个mock文件夹里面存放,index.js

详细见优快云——Vue3中使用mockjs

import { mock } from "mockjs"
let nba = [
	{id:1, name:'乔丹', number:23},
	{id:2, name:'科比', number:24},
	{id:3, name:'欧文', number:11},
	{id:4, name:'库里', number:30}
];

mock('http://localhost:5181/nba/get', 'get', () => {
	return nba;
});

mock('http://localhost:5181/nba/post', 'post', () => {
	return nba;
})

二axios的基本使用

axios发送get请求

//使用get方式发送请求
//如果默认方式没有method,那么最后结果也是get
//无参请求
<script setup lang="ts">
	import axios from "axios"
    axios({
		url:"http://localhost:5181/nba/get",
		method:'get'
	}).then(res => {
		console.log("试验");
		console.log(res);
	})
</script>

//有参请求--会改变url后缀,添加?id=1
<script setup lang="ts">
	import axios from "axios"
    axios({
        url:"http://localhost:5181/student/findStudentById",
		method:'get',
        params:{
            id:'1',
            name:'张三'
        }
	}).then(res => {
		console.log("试验");
		console.log(res);
	})
</script>

axios发送post请求

//使用post方式请求
//无参请求
<script setup lang="ts">
	import axios from "axios"
    axios({
		url:"http://localhost:5181/nba/post",
		method:'post'
	}).then(res=>{
		console.log("试验");
		console.log(res);
	})
</script>

//有参请求
//使用params传递,自动后面添加?id=1?name='张三'
<script setup lang="ts">
	import axios from "axios"
    axios({
        url:"http://localhost:5181/student/findStudentByName",
		method:'post',
        params:{
            name:'张三' //url拼接参数,不推荐
        }
	}).then(res => {
		console.log("试验");
		console.log(res);
	})
</script>

//使用data传递
<script setup lang="ts">
	import axios from "axios"
    axios({
        url:"http://localhost:5181/student/findStudentByName",
		method:'post',
        data:{
            name:'张三' //后台接受为null
        }
	}).then(res => {
		console.log("试验");
		console.log(res);
	})
</script>
/*后台控制器接收到的name为null,axios使用post携带参数请求默认使用application/json

解决方式一: params属性进行数据的传递
解决方式二: "name='张三'"
解决方式三: 服务器端给接收的参数加上@requestBody注解
*/

三、axios的请求方式

//使用axios.get方式发送无参请求
<script setup lang="ts">
	import axios from "axios"
    axios.get("http://localhost:5181/nba/get").then(res=>{
		console.log(res);
	}).catch(err=>{
		console.log(err);
	});
</script>
//使用axios.get发送有参请求
<script setup lang="ts">
	import axios from "axios"
    axios.get("http://localhost:5181/student/findStudentById",{params:{id:1,}}).then(res=>{
		console.log(res);
	}).catch(err=>{
		console.log(err);
	});
</script>

使用post发送

//使用axios.post发送无参请求
<script setup lang="ts">
	import axios from "axios"
    axios.post("http://localhost:5181/nba/post").then(res=>{
		console.log(res);
	}).catch(err=>{
		console.log(err);
	});
</script>
//使用axios.post发送有参请求 
//只修改前端代码
<script setup lang="ts">
	import axios from "axios"
    axios.post("http://localhost:5181/student/findStudentByName " ,"name='张三'&age=10").then(res=>{
		console.log(res);
	}).catch(err=>{
		console.log(err);
	});
</script>
//发送post请求携带参数 直接使用"name=张三&age=10"

//使用data传递数据,后代需要将axios自动转换的json数据转换为java对象
//修改后台代码
<script setup lang="ts">
	import axios from "axios"
    axios.post("http://localhost:5181/student/findStudentByName " ,{name:'张三'}).then(res=>{
		console.log(res);
	}).catch(err=>{
		console.log(err);
	});
</script>
//接受参数添加@requestBody注解

四、axios的并发请求

//第一种返回一个数组
<script setup lang="ts">
	import axios from "axios"
    axios.get('http://localhost:5181/nba/get'),
    axios.get('http://localhost:5181/student/findStudentById',{params:{id:1}}).then(res=>{
        console.log(res[0]);
        console.log(res[1]);
    }).catch(err=>{
        console.log(err);
    })
</script>

//第二种
<script setup lang="ts">
	import axios from "axios"
    axios.get('http://localhost:5181/nba/get'),
    axios.get('http://localhost:5181/student/findStudentById',{params:{id:1}}).then(
        axios.spread((res1,res2)=>{
            console.log(res1);
            console.log(res2);
        })
    ).catch(err=>{
        console.log(err);
    })
</script>

五、axiso的全局配置

<script setup lang="ts">
	import axios from "axios"
	
	const message = ref("123");
	axios.defaults.baseURL="http://localhost:5181";
	axios.defaults.timeout=5000;
	axios.post('api').then(res=>{
		console.log(res['data']['status']);
		message.value=res['data']['message'];
	}).catch(err=>{
		console.log(err);
	})
	
</script>

六、axios的实例

<script setup lang="ts">
    import axios from "axios"
	// 创建axios的实例
	let newVar = axios.create({
		baseURL: 'http://localhost:5181',
		timeout:5000
	});
	
	newVar({
		url:'nba/get'
	}).then(res=>{
		console.log("实例");
		console.log(res);
	})
</script>

七、axios的拦截器

axios给我们提供了两大类拦截器:
  • 请求方向的拦截(成功请求,失败的)

  • 响应方向的(成功的 失败的)

拦截器的作用:
  • 用于我们在网络请求的时候在发起请求或者响应时对操作进行响应的处理

  • 发起请求时可以添加网页加载的动画,强制登录

  • 响应的时候可以进行相应的数据处理

//请求方向拦截器
<script setup lang="ts">
    import axios from "axios"
    axios.interceptors.request.use(
        config=>{
            console.log("进入请求拦截器");
            console.log(config);
            return config;
        }),
        err=>{
            console.log("请求方向失败");
            console.log(err);
        }
        axios.get("http://localhost:5181/nba/get").then(res=>{
            console.log(res);
        })
</script>
//响应方向拦截器
<script setup lang="ts">
    import axios from "axios"
    axios.interceptors.response.use(
	config=>{
		console.log("进入响应拦截器");
		console.log(config);
		return config.data;
	}),
	err=>{
		console.log("响应方向失败");
		console.log(err);
	}
	axios.get("http://localhost:5181/nba/get").then(res=>{
		console.log(res);
	})
</script>

八、axios在vue中的模块封装

  • 第一种方式
//封装位置 文件绝对位置../../request.uts
import axios from 'axios'
export function request(config, success, fail){
	axios({
		url:config
	}).then(res=>{
		success(res);
	}).catch(err=>{
		fail(err);
	})
}

//调用文件
import {request} from '../../request.uts'
	request('http://localhost:5181/nba/get',res=>{
		console.log(res);
	},err=>{
		console.log(err);
	})
  • 第二种方式
//封装位置
import axios from 'axios'
export function request(config){
	axios.defaults.baseURL = "http://localhost:5181"
	axios(config.url).then(res=>{
		config.success(res);
	}).catch(err=>{
		config.fail(err);
	})
}
//文件位置
import {request} from '../../request.uts'
	request({
		url:'nba/get',
		success:res=>{
			console.log(res);
		},
		fail:err=>{
			console.log(err);
		}
	})
  • 第三种方式
//封装位置
import axios from 'axios'
export function request(config){
	return new Promise((resolve, reject) => {
		let newVar = axios.create({
			baseURL:"http://localhost:5181",
			timeout:5000
		})
		newVar(config).then(res=>{
			resolve(res);
		}).catch(err=>{
			reject(err);
		})
	})
}
//文件位置
import {request} from '../../request.uts'
request({
		url:'nba/get'
	}).then(res=>{
		console.log(res);
	}).catch(err=>{
		console.log(err);
	})
  • 第四种方式
//封装位置
import axios from 'axios'
export function request(config){
    let newVar = axios.create({
			baseURL:"http://localhost:5181",
			timeout:5000
		});
    return newVar(config);
}
//调用位置
import {request} from '../../request.uts'
request({
		url:'nba/get'
	}).then(res=>{
		console.log(res);
	}).catch(err=>{
		console.log(err);
})

总结:

  • 这里最推荐的是最后一种方法,简单高效。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值