4、在vue中官方建议用axios发送ajax
5、axios的特性
-
从浏览器中创建XMLHTTPRequests
-
从node.js创建http请求
-
支持Promise API
-
拦截请求数据 和响应
-
转换请求数据和响应数据
-
取消请求
-
自动转换JSON数据
-
客户端支持防御XSRF
==============================================================================
1、从axios官网下载axios
中文网站:https://www.kancloud.cn/yunye/axios/234845
安装: https://unpkg.com/axios/dist/axios.min.js
2、将文件放入项目的webapp中
<script src="js/axios.min.js"></script>
3、在页面中引用
4、发送异步请求
-
url?xxx
-
rest请求【
GET,POST,DELETE,PATCH
】
5、准备一个SpringBoot的控制层与axios进行交互
- 实体类
public class User {
private Integer id;
private String username;
- 控制层
/**
-
@author 王恒杰
-
@date 2021/12/16 16:25
-
@Description:
*/
@Controller
@CrossOrigin //设置当前控制器支持所有域访问 解决跨域问题
public class UserAction {
@RequestMapping(“test1”)
@ResponseBody
public String test1(Integer id,String username){
System.out.println(“test1”);
System.out.println(“id:”+id);
System.out.println(“username:”+username);
return “test1 response”+id+username;
}
}
6、 GET方式的请求
axios.get(“http://localhost:8080/aa/test1?id=1&username=whj”)
.then(function (response) {
console.log(response.data)
})
.catch(function (err) {
console.log(err)
})
7、POST方式请求
- 前台传的数据是json
//发送POST方式请求
axios.post(“http://localhost:8080/aa/test2”,{
id:2,
username:“王恒杰”
}).then(function (response) {
console.log(response.data);
}).catch(function (err) {
console.log(err)
})
- **注意: post接收数据时,需要在参数上添加 ** requestBody
8. axios并发请求
并发请求
: 将多个请求在同一时刻发送到后端服务接口,最后在集中处理每个请求的响应结果
function getUserAccount() {
return axios.get(‘/user/12345’);
}
function getUserPermissions() {
return axios.get(‘/user/12345/permissions’);
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
9.自定义配置对象发送请求
//自定义配置对象发送请求(创建实例 发送异步请求) 【企业开发必背】
var instaus = axios.create({
baseURL:“http://localhost:8080/aa/”,
// timeout: 5000 //设置响应超时时间 如果超过了5000秒报异常
});
instaus.get(“test1?id=3&username=yfj”)
.then(function (response) {
console.log(response.data);
})
最后
开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】
给大家分享一些关于HTML的面试题。
.then(function (response) {
console.log(response.data);
})
最后
开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】
给大家分享一些关于HTML的面试题。
[外链图片转存中…(img-oFYiwYbv-1714375694249)]
[外链图片转存中…(img-YoAVDifK-1714375694250)]