为什么要进行二次封装?
请求拦截器:可以在发请求之前处理一些业务
响应拦截器:服务器返回数据后可以处理业务
1 安装使用axios
1.1 安装axios
cnpm install --save axios
1.2 src目录创建api/request.js
在项目中一般有api文件夹[axios]
import axios from "axios";
// 1. 创建axios实例
const requests = axios.create({
// 配置对象
// 请求路径都带/api
baseURL: '/api',
// 请求超时时间
timeout: 5000
});
// 2. 请求拦截器
requests.interceptors.request.use((config) => {
// config配置对象,里面有个很重要的属性header请求头
return config;
})
// 3. 响应拦截器
requests.interceptors.response.use((res) => {
// 请求成功的回调函数
return res.data;
}, err => {
return Promise.reject(new Error('fail'));
})
// 对外暴露
export default requests;
2 api接口统一管理
之前写的vue页面都是静态的
如果项目很小,完全可以在组件生命周期函数中发送请求,如果项目大,可以在axios.get(), axios.post(),但是如果一个接口多次使用,并且有修改,会很麻烦,所以还是统一管理更方便
3 跨域
前端服务器: http://localhost:8080/#/home
后端服务器: http://localhost:11000/api/hosp/dept/deptListTree
如果两个不在一个主机,可以用webpack配置代理
vue.config.js中加入
module.exports = {
lintOnSave:false,
// 配置代理
devServer: {
proxy: {
// 带有/api 去找http://localhost:11000
'/api': {
target: 'http://localhost:11000'
}
}
}
}
后端controller还要加上@CrossOrigin
注解