Axios 是一个基于 promise(异步实现) 的 HTTP 库,可以用在浏览器和 node.js 中使用,原生的js或者使用jquery来发生请求进行前后端数据交互,代码写起来过于复杂。
axios官网链接
1、安装axios
方式一:使用 npm安装
npm install axios
方式二:直接通过script全局引用
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2、axios发送get请求
案例一:get请求
const res = axios.get('http://127.0.0.1:5000/api/...')
//then 请求成功的处理。通过链式调用catch请求失败的处理
// 请求成功返回一个Promise对象,通过回调函数接受,data获取数据,status获取状态码
res.then(function(response){console.log('请求成功:'response.data)
}).catch(function(error){
console.log('请求失败的',error)
})
案例二:get请求参数传递
使用axios发送get请求传递查询字符串参数,有如下两种方式
方式一:直接写在url地址中,问号隔开
const res = axios.get("http://127.0.0.1:5000/api/...?name='test'")
方式二:使用params进行传递
const res = axios.get('http://127.0.0.1:5000/api/pro_list',{params: {"name":"musen"}} )
3、axios发送post请求
1.传递json格式的参数
axios.post('http://127.0.0.1:5000/api/login',{pwd: 'lemonban',user: 'python01'} )
2.传递表单类型的参数
// 构建一个表单参数对象
var params = new URLSearchParams();
params.append('user', 'ming');
params.append('pwd', '12345'); axios.post('http://127.0.0.1:5000/api/login', params)
3.请求配置项
举例:
headers:是即将被发送的自定义请求头
baseURL:通过设置一个 baseURL便于为 axios 实例的方法传递相对 url
axios.post('/api/login',{pwd: 'lemonban',user: 'python01'},{headers:{token:'token'},baseURL:'http://127.0.0.1:5000'})
4、全局的axios配置
配置后默认所有接口请求都会生效
// 配置baseURL
axios.defaults.baseURL = 'http://127.0.0.1:5000'
//配置请求头信息
axios.defaults.headers.common['token'] = 'token'
//配置请求类型
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
const res = axios.get('/api/...').then(function(response){console.log('请求成功:'response.data)
}).catch(function(error){
console.log('请求失败的',error)
})
针对多个后端服务的场景可以创建多个axios对象来配置不同的信息
// 创建axios对象A
const requestA = axios.create({baseUrl:'http://127.0.0.1:5000'})
// 创建axios对象B
const requestB = axios.create({baseUrl:'http://127.0.0.1:5000'})
requestA.then(function(response){console.log('请求成功:'response.data)}).catch(function(error){console.log('请求失败的',error)})
requestB.then(function(response){console.log('请求成功:'response.data)}).catch(function(error){console.log('请求失败的',error)})
5、axios拦截器
1.请求拦截器
请求拦截器的作用是在请求发送前进行一些操作
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// config为请求对象
// 在发送请求之前可以执行操作
return config},function (error) {
// 对请求错误做些什么
return Promise.reject(error)})
举例:获取本地token值添加到请求头
<script type="text/javascript">
// 创建对象
const requestA = axios.create({
baseURL: 'url'
})
// 创建并添加请求拦截器
requestA.interceptors.request.use(function(config) {
console.log('请求拦截器', config)
// 判断登录以外的接口
if (config.url === '/users/login/') return config
config.headers['Authorization'] = 'Bearer ' + window.localStorage.getItem('token') // 获取token并添加到请求头
return config
});
requestA.post('/users/login/', {
username: 'test',
password: '12345'
}).then(function(response) {
let token = response.data.token // 获取token
window.localStorage.setItem('token', token) //将token存到localStorage
}).catch(function(error) {
console.log('请求失败')
})
// 请求需求鉴权的接口
requestA.get('/user').then(function(response) {
console.log('请求成功')
})
2.响应拦截器
响应拦截器的作用是在接收到响应后进行一些操作
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response}, function (error) {
// 对响应错误做点什么
return Promise.reject(error)})
如下:
requestA.interceptors.response.use(function(response){
console.log('响应拦截器',response)
alert('请求成功了')
return response
}),function(error){
return Promise.reject(error)}
6、async await的使用
async用于声明一个函数是异步的。而await从字面意思上是“等待”的意思,就是用于等待异步完成。并且await只能在async函数内使用,简单理解就是,async 声明的函数内的异步会按照同步执行顺序
举例:请求通过async、await的方式发送
async function login(){
let response = await requestA.post('/users/login/',{username: 'test',password: '123456'})
async function project(){
let res = await requestA.get('/projects/')
}