测开之・《前后端交互axios》
Posted 七月的小尾巴
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了测开之・《前后端交互axios》相关的知识,希望对你有一定的参考价值。
前端后端交互axios
前言
Axios 是一个基于 promise(异步实现) 的 HTTP 库,可以用在浏览器和 node.js 中使用,原生的js或者使用jquery来发生请求进行前后端数据交互,代码写起来过于复杂。
axios的使用
安装axios
- 方式一
npm install axios
- 方式二
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
axios发送get请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<script type="text/javascript">
const request= axios.get('http://127.0.0.1:5000/api/projects')
// 请求成功时(响应状态码为2系列)会执行then方法传入的回调函数
request.then(function (response){
console.log(response)
})
// 当请求失败,会执行catch方法传入回调函数
res1.catch(function (error){
console.log(error)
console.log(error.response)
})
// 也可以直接使用链式调用
axios.get('http://127.0.0.1:5000/api/projects').then(function (response){
console.log(response)
}).catch(function (error){
console.log(error);
console.log(error.response)
})
</script>
</body>
</html>
get请求带参数
- 方式一:参数直接放在url中
// 把请求参数直接放在url中
const res = axios.get('http://127.0.0.1:5000/api/pro_list?name=musen')
- 方式二:使用params进行传递
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<script type="text/javascript">
// 链式调用
axios.get("http://127.0.0.1:5000/api/interface",{
// 查询字符串参数传递
params:{
id: 1001
}
}).then(function (response){
// 请求成功时执行
console.log('res', response)
// 获取响应状态码
console.log(response.status)
// 获取响应数据
console.log(response.data)
// 请求失败时执行
}).catch(function (error){
console.log(error);
console.log(error.response)
})
</script>
</body>
</html>
发送post请求
- 传递json格式的参数
const res1 = axios.post('http://127.0.0.1:5000/api/user/login',
{pwd: 'lemonban',user: 'python01'}
)
- 传递表单类型的参数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<script type="text/javascript">
// 构建一个表单参数对象
var params = new URLSearchParams()
params.append('user', 'python')
params.append('pwd', 'lemonban')
axios.post('http://127.0.0.1:5000/api/user/login', params)
// console.log(res1)
</script>
</body>
</html>
全局axios配置
- 配置基本的host地址
axios.defaults.baseURL ='https://api.example.com'
- 配置请求头信息
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<script type="text/javascript">
// 全局的请求配置信息
axios.defaults.baseURL ='http://127.0.0.1:5000'
axios.defaults.headers.common['Authorization'] = 'test'
// 链式调用
axios.get("/api/interface",{
// 查询字符串参数传递
params:{
id: 1001
},
}).then(function (response){
// 请求成功时执行
console.log('res', response)
// 获取响应状态码
console.log(response.status)
// 获取响应数据
console.log(response.data)
// 请求失败时执行
}).catch(function (error){
console.log(error);
console.log(error.response)
})
</script>
</body>
</html>
多服务场景调用
在日常项目中,我们可能会遇到一个项目需要调用多个服务的接口,那么我们可以创建axios实例对象进行调用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<script type="text/javascript">
// 针对多个后端服务的场景
const requestA = axios.create({
baseURL: "http://127.0.0.1:5000",
headers: {"test": 111}
})
const requestB = axios.create({
baseURL: "http://127.0.0.1:6000"
})
// 链式调用
requestA.post("/api/interface",{
// 查询字符串参数传递
params:{
id: 1001
},
}).then(function (response){
// 请求成功时执行
console.log('res', response)
}).catch(function (error){
console.log(error);
console.log(error.response)
})
// 链式调用
requestB.post("/api/interface",{
// 查询字符串参数传递
params:{
id: 1001
},
}).then(function (response){
// 请求成功时执行
console.log('res', response)
}).catch(function (error){
console.log(error);
console.log(error.response)
})
</script>
</body>
</html>
后端鉴权的接口处理
假设我们有些接口需要鉴权,那么可以使用如下方法,获取token信息
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<script type="text/javascript">
const requestB = axios.create({
baseURL: "http://47.112.233.130:8888",
})
requestB.post('/users/login',{
username: "yushaoqi",
password: '12345',
}
)
.then(function (response){
console.log(response);
// 提取token
let token = response.data.token
// 保存token到localStorage
window.localStorage.setItem('token', token)
// 保存到sessionStorage中,关闭浏览器之后,token会被清空
// window.sessionStorage.setItem('token', token)
})
.catch(function (error){
console.log(error.response)
})
requestB.post('project/', {
// 接口2依赖token处理
headers:{
Authorization: 'Bearer' + window.localStorage.getItem('token')
}
}).then(function (response){
console.log(response)
}).catch(function (error){
console.log(error.response)
})
</script>
</body>
</html>
axios请求拦截器
前面我们请求鉴权接口的时候,每个接口都需要在其中写入token,如果只是单个接口还好,但是随着我们项目越来越庞大,几乎所有接口都需要用到token,那们我们可以把这个条件判断抽离出来。这里可以用到请求拦截器:
下面我们仍然结合登录接口,来实现案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>测开平台</title>
<script src='./vue.js'></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<style type="text/css">
.login{
width: 600px;
height: 400px;
box-shadow: 0 0 15px #000000;
margin: 150px auto;
/*设置圆角*/
border-radius: 5px;
/*内容居中*/
text-align: center;
}
.title{
color: #00aaff;
font: bold 24px/30px "microsoft sans serif";
padding: 50px 0;
}
/*设置输入框的样式*/
.login input{
width: 70%;
height: 35px;
margin-bottom: 30px;
border: solid 1px #d1d1d1;
padding: 0;
border-radius: 3px;
}
/*设置input键盘输入时,边框的样式*/
.login input:focus{
outline: none;
border: solid 1px #ffaa00;
}
/*设置按钮样式*/
.login input[type='submit']{
background: #00AAFF;
color: #fff;
}
</style>
</head>
<body>
<div id="app">
<div class="login">
<div class="title">接 口 自 动 化 平 台</div>
<form action="">
<input type="text" v-model="loginForm.user" placeholder=" 请输入用户名">
<input type="password" v-model="loginForm.pwd" placeholder=" 请输入密码">
<input type="button" @click="login" value="登录"/>
</form>
</div>
<hr>
<table border="" cellspacing="" cellpadding="">
<tr>
<th>ID</th>
<th>项目名称</th>
<!-- <th>负责人</th>-->
<!-- <th>描述信息</th>-->
</tr>
<tr :key="item.id" v-for="item in projects ">
<td>{{item.id}}</td>
<td>{{item.title}}</td>
</tr>
</table>
</div>
<script type="text/javascript">
const requestB =以上是关于测开之・《前后端交互axios》的主要内容,如果未能解决你的问题,请参考以下文章
前后端分离之使用axios进行前后端交互实现评论显示——django+mysql+vue+element