1.安装axios
vue add axios
2.axios全局配置
import '../plugins/axios'
//baseURL 将自动加在url前面,除非url是一个绝对 UR
//每次发送请求都会带一个/api/v1的前缀
axios.defaults.baseURL = "/api/v1";
//如果请求话费了超过timeout的时间,请求将被中断
axios.defaults.timeout = 5000 ;
// 请求拦截器
axios.interceptors.request.use(function(config){
//
let token = localStorage.getItem("accessToken") || "";
if(token){
config.headers.accessToken = token ;
}
console.log("request");
if(config.method === "post"){
config.data = Json.stringify(config.data) ;
}
return config ;
},function(error){
return Promise.reject(error) ;
})
// 响应拦截器
axios.interceptors.response.use(function(response){
// 如果返回的状态码为200,说明接口请求成功,可以正常拿到数据
if(response.status === 200){
return Promise.resolve(response) ;
}else {
return Promise.reject(response) ;
}
},function(error){
if (error.response.status) {
switch (error.response.status) {
// 401: 未登录
// 未登录则跳转登录页面,并携带当前页面的路径
// 在登录成功后返回当前页面,这一步需要在登录页操作。
case 401:
router.replace({
path: '/login',
query: {
redirect: router.currentRoute.fullPath
}
});
break;
// 403 token过期
// 登录过期对用户进行提示
// 清除本地token和清空vuex中token对象
// 跳转登录页面
case 403:
// 清除token
localStorage.removeItem('token');
// store.commit('loginSuccess', null);
// 跳转登录页面,并将要浏览的页面fullPath传过去,登录成功后跳转需要访问的页面
setTimeout(() => {
router.replace({
path: '/login',
query: {
redirect: router.currentRoute.fullPath
}
});
}, 1000);
break;
}
return Promise.reject(error.response);
}
})
export default axios;
3.main.js引入
在vue add axios
后会自动在main.js
中引入
import './plugins/axios'
配置后改成自定义配置后的axios
import './config/axios.js'
4.vue.config.js解决跨域问题
vue.config.js是在根目录下 参考配置
//跨域
module.exports = {
devServer: {
proxy: {
//"/api/v1"是检测/api/v1/..的请求
//建议与第二步中的axios.defaults.baseURL = "/api/v1"对应
'/api/v1': {
// 你要请求的后端接口ip+port
target: 'http://localhost:8081/api/v1',
// 允许跨域,在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
changeOrigin: true,
// 开启webSocket
ws: true,
pathRewrite: {
//请求路径在发送请求前重写,可选
//此处将"^/api/v1/"替换成"",然后拼接到target上
//相当于请求/api/v1/hello/index
//把"/api/v1"替换掉,替换后的结果"/hello/index"拼接到target
//http://localhost:8081/api/v1/hello/index
'^/api/v1': '',
}
}
}
}
}
5.api目录
可把请求接口全部放在此目录
user.js
export function hello(data){
return axios({
// url发送请求前会自动拼凑axios全局配置的baseURL
// 相当于/api/v1/hello/index
//vue.config.js检测到/api/v1/*的请求
//pathRewrite先把/api/v1替换成""
//然后/hello/index拼接到target上
//最终为"http://localhost:8081/api/v1/hello/index"
url:'/hello/index',
data:data,
method:'GET'
})
}
6.调用
<script>
import {hello} from '@/api/user.js'
export default{
data(){
return{
}
},
mounted() {
hello().then(res=>{
console.log(res);
});
},
}
</script>
springboot 2.x代码
#application.yml
server:
port: 8081
servlet:
context-path: /api/v1
//Controller
@RestController
@RequestMapping("/hello")
public class HelloController {
@GetMapping("/index")
public Object hello(){
return "hello" ;
}
}
7.效果