1. Axios
1.1介绍
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
特点:
1.从浏览器中创建 XMLHttpRequests
2.从 node.js 创建 http 请求
3.支持 Promise API
4.拦截请求和响应
5.转换请求数据和响应数据
6.取消请求
7.自动转换 JSON 数据
8.客户端支持防御 XSRF
结构说明:
1. JS中原生提供了Ajax操作. 弊端: 操作特别的复杂 易用性较差.
2. jQuery中的Ajax 封装了原生的JS Ajax 提高了开发的效率
3. Axios是VUE中默认支持的Ajax的请求的方式.
1.2 调用步骤
<body>
<script src="../js/axios.js"></script>
<script>
// 1、Axios将原来的嵌套结构改为链式结构
// 2、回调中的返回值,被忽视服务器的返回值,而是promise对象
axios.get("http://localhost:8090/axios")
.then(function(data){
console.log(data.data)
})
</script>
</body>
1.3 Axios的传参方式
1.3.1 Axios-Get的简单传参方式
前端:
axios.get("http://localhost:8090/axios/getUserID?id=100")
.then(function(result){
console.log(result.data)
})
后端:
@GetMapping("/axios/getUserID")
public String getUserID(Integer id){
return "返回信息id:"+id;
}
1.3.2 Axios-Get的RestFul传参方式
前端:
axios.get("http://localhost:8090/axios/getUserID/200")
.then(function(result){
console.log(result.data)
})
/**
* restFul风格实现业务传参
* 模板函数作用:保留代码原始结构+为参数动态赋值
* (不需要再getUserID/"+name+"/"+age,简化了)
*/
let name="张三"
let age=22
axios.get(`http://localhost:8090/axios/getUserID/${name}/${age}`)
.then(function(result){
console.log(result.data)
})
后端:
@GetMapping("/axios/getUserID/{id}")
public String getUserID2(@PathVariable Integer id){
return "返回信息id:"+id;
}
@GetMapping("/axios/getUserID/{name}/{age}")
public String getUserID3(@PathVariable String name,@PathVariable Integer age){
return "返回信息name:"+name+",age:"+age;
}
1.4 Axios四种请求方式(Get、Post、Delete、Put)
1.4.1 Get的对象传参
前端:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script src="../js/axios.js"></script>
<script>
let user={ id:1002,name:"张三",age:23,sex:"男"}
axios.get("http://localhost:8090/run/getObj",{
params:user
})
.then(function(result){
console.log(result.data)
})
</script>
</body>
</html>
后端:
@GetMapping("/run/getObj")
public User test2(User user){
return user;
}
1.4.2 Delete请求
前端:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- 语法:一般用户通过Delete请求做删除操作,
删除的语法与Get请求语法一致
请求方式:
1.不带参数点的请求 .delete("url地址")
2.携带个别参数 .delete("url地址?id=100")
3.restFul结构 .delete("url地址/*/*/*/*")
4.采用对象方式进行参数传递
-->
<script src="../js/axios.js"></script>
<script>
// 1.不带参数的请求
axios.delete("http://localhost:8090/run/delete")
.then(function(result){
console.log(result.data)
})
// 2.携带个别参数
axios.delete("http://localhost:8090/run/delete2?id=100")
.then(function(result){
console.log(result.data)
})
//3.restFul结构
let id=1008
let name="张三"
let age=23
let sex="男"
axios.delete(`http://localhost:8090/run/delete/${id}/${name}/${age}/${sex}`)
.then(function(result){
console.log(result.data)
})
// 4.采用对象方式进行参数传递
let user={ id:1009,name:"张三",age:23,sex:"男"}
axios.delete("http://localhost:8090/run/delete3",{
params:user
})
.then(function(result){
console.log(result.data)
})
</script>
</body>
</html>
后端:
//不接收参数
@DeleteMapping("run/delete")
public String test6()
{
return "不接收参数";
}
//接收个别参数
@DeleteMapping("run/delete2")
public String test5(Integer id)
{
return "接受的参数为:"+id;
}
//restFul参数格式
@DeleteMapping("run/delete/{id}/{name}/{age}/{sex}")
public User test7(User user)
{
return user;
}
//对象参数格式
@DeleteMapping("run/delete3")
public User test8(User user)
{
return user;
}
1.4.3 Post请求
1、post的对象传参
前端:
<!-- post主要用于pom表单的提交,保护秘密信息 -->
<!-- 总结如果需要对象传参:
1.get采用{params:对象}
2.post采用 axios.post(url,对象)-->
<script src="../js/axios.js"></script>
<script>
let user={ id:1005,name:"张三",age:23,sex:"男"}
let url="http://localhost:8090/run/post"
axios.post(url,user)
.then(function(result){
console.log(result.data)
})
后端:
/**
* post提交传过来的是JSON串,不能直接用对象接参
* 解决方法:
* 1.JSON串->对象 @RequestBody ✔
* 2.独对象->JSON串 @ResponseBody
*/
@PostMapping("run/post")
public User test4(@RequestBody User user)
{
return user;
}
2、post的restFul传参方式
前端:
<!-- post请求restFul写法 -->
let url2="http://localhost:8090/run/post2/1005/赵四/44/男"
axios.post(url2)
.then(function(result){
console.log(result.data)
})
后端:
@PostMapping("run/post2/{id}/{name}/{age}/{sex}")
public User test3(User user)
{
return user;
}
1.5 async-await用法-箭头函数
1.5.1 概念解释
1.async/await 是ES7引入的新语法 可以更加方便的进行异步操作
2.async 关键字用在函数上. 返回值是一个promise对象
3.await 关键字用在async 函数中
1.5.2 箭头函数
/**
* axios的get请求语法
* 知识点:
* 1.箭头函数 主要简化回调函数的写法
* 思路: 重复的 固定的可以简化
* 规则: 如果参数只有一个则括号可以省略
*/
let url = "http://localhost:8090/axios/getUserID?id=100"
axios.get(url)
.then( result => {
alert(result.data)
})
1.5.3 async-await 操作
// 2.async--await简化
// await: 标识ajax请求
// async: 标识函数
async function getUserID(){
let url="http://localhost:8090/axios/getUserID?id=100"
// let promise=await axios.get(url)
// console.log(promise)
// console.log(promise.data)
let {data: resultData,status: code}=await axios.get(url)
console.log(resultData)
console.log(code)
}
getUserID()
1.5.4 配置axios请求路径
// 定义ajax请求的路径,为ajax请求添加前缀
axios.defaults.baseURL="http://localhost:8090"
async function getUserID(){
let url="/axios/getUserID?id=100"
// let promise=await axios.get(url)
// console.log(promise)
// console.log(promise.data)
let {data: resultData,status: code}=await axios.get(url)
console.log(resultData)
console.log(code)
}
getUserID()
1.6 Axios练习
1.6.1VUE+Axios 需求分析
说明:
- 利用VUE.js构建页面
- 利用Axios实现userList数据的获取, 利用VUE.js展现列表信息
- 完成页面数据的删除操作
- 完成页面数据的修改操作
前端效果展示:
绘制前端页面:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="app">
<h1 align="center">修改信息</h1>
<div align="center">
<table border="0px" width="50%" align="center">
<tr align="center">
<td align="absmiddle">ID号:<a v-text="upUser.id"></a></td>
</tr>
<tr align="center">
<td>姓名:<input v-model.trim="upUser.name" type="text"/></td>
</tr>
<tr align="center">
<td>年龄:<input v-model.number="upUser.age" type="text"/></td>
</tr>
<tr align="center">
<td>性别:<input v-model.trim="upUser.sex" type="text"/></td>
</tr>
<tr align="center">
<td ><button type="button" @click="updateUser()">提交</button></td>
</tr>
</table>
<h1>新增信息</h1>
ID:<input type="text" v-model.number="user.id"/>
name:<input type="text" v-model.trim="user.name"/>
age:<input type="text" v-model.number="user.age"/>
sex:<input type="text" v-model.trim="user.sex"><br />
<button @click="addUser()">提交</button>
</div>
<br />
<table border="2px" align="center" width="80%">
<tr align="center">
<td colspan="5"><h1>信息展示列表</h1></td>
</tr>
<tr>
<th>ID</th>
<th>name</th>
<th>age</th>
<th>sex</th>
<th>action</th>
</tr>
<tr v-for="user in userList" align="center">
<td v-text="user.id"></td>
<td v-text="user.name"></td>
<td v-text="user.age"></td>
<td v-text="user.sex"></td>
<td>
<button type="button" @click="delUser(user.id)">删除</button>|
<button type="button" @click="getUpUser(user)">修改</button>
</td>
</tr>
</table>
</div>
<script src="../js/axios.js"></script>
<script src="../js/vue.js"></script>
<script>
axios.defaults.baseURL="http://localhost:8090"
const APP=new Vue({
el:"#app",
data:{
userList:[],
user:{id:0,name:'',age:0,sex:''},
upUser:{id:0, name:'',age:0,sex:''}
},
// 调用生命周期函数
methods:{
async addUser(){
alert("添加成功!")
await axios.post("/vue/addUser",this.user)
this.getUserList()
},
async getUserList(){
// alert("展示成功!")
let{data: result}=await axios.get("/vue/getUserList")
this.userList=result
},
async delUser(id){
alert("删除成功!")
await axios.delete(`/vue/delUser?id=${id}`)
this.getUserList()
},
async getUpUser(clickUser){
this.upUser.id=clickUser.id
this.upUser.name=clickUser.name
this.upUser.age=clickUser.age
this.upUser.sex=clickUser.sex
},
async updateUser(){
alert("修改成功!")
await axios.put("/vue/updateUser",this.upUser)
this.getUserList()
}
},
mounted() {
this.getUserList()
}
})
</script>
</body>
</html>
后端配置:
@RestController
@CrossOrigin
@RequestMapping("/vue/")//包含全部类型
public class VUEController {
@Autowired
private UserService userService;
@GetMapping("getUserList")
public List<User> getUerList(){
return userService.getUerList();
}
@PostMapping("addUser")
public void addUser(@RequestBody User user){
userService.addUser(user);
}
@DeleteMapping("delUser")
public void delUser(Integer id){
userService.delUser(id);
}
@PutMapping("updateUser")
public void updateUser(@RequestBody User user){
userService.updateUser(user);
}
}