vue+Java 前后端分离,多次请求Session不一致的问题

本文介绍如何在Vue项目中使用axios实现跨域请求并携带凭证信息,通过配置axios及服务端filter来解决跨域问题,并确保登录状态在图片上传等操作中保持有效。

Vue项目用的axios发送请求
在main.js中增加以下配置:

import axios from 'axios';
axios.defaults.withCredentials=true;

使用时,设置withCredentials: true(请求时携带凭证信息)

axios({
  url: url,
  data: data,
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  method: 'POST',
  withCredentials: true
}).then(response => {
  resolve(response)
}

服务端添加filter

    private final List<String> allowedOrigins = Arrays.asList("http://localhost:8089","http://localhost:8088");// 允许跨域的地址
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Accept, Content-Type");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", allowedOrigins.contains(origin) ? origin : "");
        // 是否允许浏览器携带用户身份信息(cookie)
        response.setHeader("Access-Control-Allow-Credentials","true");
        // 图片上传会用到
        if( "OPTIONS".equals(request.getMethod())){   
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

方法中有一行if( "OPTIONS".equals(request.getMethod())) 的判断,是因为我在做图片上传时,登录认证会失效导致跳转到登录页。
后来发现原因是在做图片上传时,会在POST请求之前,先发送一个OPTION的预请求,这个请求的作用主要是 获取服务器支持的HTTP请求方法,用来检查服务器的性能或判断后续请求是否安全。
如果是OPTIONS请求,不会执行filterChain.doFilter(servletRequest, servletResponse),以至于之后的shiro校验不生效,所以会没有权限。

<think>嗯,用户明确提出了想从零开始学习SpringBoot+Vue全栈开发的需求,而且特别强调了“前后端分离”这个关键词。从之前的对话历史看,用户已经接触过一些相关资料引用(虽然系统提示那些是真实需求),但能感觉到用户是个刚入行的开发者,可能对复杂的项目搭建有畏难情绪。用户可能真正需要的是:一个能降低学习门槛的路线图,最好有明确的学习步骤和资源推荐。ta提到的“从零开始”暗示需要基础指导,而“全栈开发教程”说明希望有系统性材料。我注意到四点关键信息:1)用户是初学者(引用中多次提到刚入行小伙伴困难)2)需要整合前后端知识3)需要项目实战导向4)可能需要规避常见坑点。因此回复要避免纯理论,重点放在“如何做”。从技术角度,SpringBoot+Vue全栈涉及几个核心模块:后端框架、前端框架、通信协议、工程化部署。每个模块都要给出具体实施建议。比如SpringBoot的依赖注入这块对新手容易困惑,应该提醒重点学习@Autowired;而Vue的axios封装又是前后端联调的关键点。资源推荐需要分层:快速入门文档(如Vue官方指南)、系统教程(王松的实战书)、持续学习途径(尚硅谷视频)。特别要加入SpringBoot的版本选择建议,因为3.x版本和2.x的配置差异可能导致新手卡住。项目实战示例采用电商管理后台是因为:1)功能模块覆盖全面(权限/商品管理必备)2)社区资源丰富3)能体现CRUD和状态管理典型场景。特意避开太复杂的支付或即时通讯功能。最后的避坑指南是新手的刚需,比如CORS和路由冲突都是实际开发中高频问题。部署部分强调容器化因为现在企业主流用Docker部署SpringBoot,而Vue的Nginx配置是前后端分离标配。补充学习建议时想到用户可能有时间焦虑,所以强调里程碑划分,两周一个周期比较合理。调试工具推荐Chrome插件是因为图形化界面比命令行更友好。额外提供的思维导图能帮用户建立知识图谱。</think> 以下是针对**SpringBoot+Vue全栈开发**的完整学习路径与实战指南,结合前后端分离核心要点,帮助你高效从零搭建项目👇 --- ### **一、基础环境准备** 1. **后端环境** - JDK 17(SpringBoot 3.x要求JDK 17+) - Maven 3.8+ 或 Gradle 8.x - IDE:IntelliJ IDEA(推荐)或 VS Code 2. **前端环境** - Node.js 18.x + npm 9.x - Vue CLI 5.x:`npm install -g @vue/cli` - IDE:VS Code + Volar插件 --- ### **二、后端开发(SpringBoot)** #### **核心步骤** ```java // 1. 创建SpringBoot项目(Spring Initializr) 依赖选择:Spring Web, Spring Data JPA, MySQL Driver, Lombok // 2. 配置文件:application.yml server: port: 8080 spring: datasource: url: jdbc:mysql://localhost:3306/db_name?useSSL=false username: root password: 123456 jpa: hibernate: ddl-auto: update // 3. 实体类示例(JPA) @Entity @Data // Lombok注解 public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String email; } ``` #### **关键技能点** 1. RESTful API设计:`@RestController`, `@GetMapping`, `@PostMapping` 2. 跨域配置:`@CrossOrigin` 或全局配置类 3. 统一响应封装:`ResponseEntity<T>` 或自定义Result类 4. 分页查询:`Pageable` + `PageRequest` --- ### **三、前端开发(Vue3 + TypeScript)** #### **项目初始化** ```bash vue create frontend # 选择:Vue3, TypeScript, Vue Router, Pinia, ESLint cd frontend npm install axios pinia-plugin-persist ``` #### **核心目录结构** ``` src/ ├── api/ # 接口封装 ├── store/ # Pinia状态管理 ├── router/ # 路由配置 ├── views/ # 页面组件 └── utils/ # 工具类(如request.ts) ``` #### **关键代码示例** ```typescript // 1. 封装Axios请求 (utils/request.ts) const service = axios.create({ baseURL: "http://localhost:8080/api", timeout: 5000 }); // 2. Pinia状态管理 export const useUserStore = defineStore('user', { state: () => ({ token: localStorage.getItem('token') || '' }), actions: { async login(username: string, password: string) { const res = await service.post('/login', {username, password}); this.token = res.data.token; } } }); // 3. 路由守卫拦截(router/index.ts) router.beforeEach((to) => { const store = useUserStore(); if (to.meta.requiresAuth && !store.token) return '/login'; }); ``` --- ### **四、前后端联调关键点** 1. **接口对接** - 使用Swagger生成API文档:`springdoc-openapi` - Postman测试后端接口 2. **跨域问题** 后端配置(全局): ```java @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:8081") // Vue端口 .allowedMethods("*"); } } ``` 3. **状态保持** - JWT鉴权:后端生成token,前端存localStorage - Axios拦截器自动携带token: ```typescript service.interceptors.request.use(config => { config.headers.Authorization = `Bearer ${store.token}`; return config; }); ``` --- ### **五、项目部署方案** 1. **后端** - 打包:`mvn clean package` → 生成`target/*.jar` - 运行:`java -jar your-app.jar --spring.profiles.active=prod` 2. **前端** - 打包:`npm run build` → 生成`dist`目录 - Nginx配置: ```nginx server { listen 80; location / { root /path/to/dist; index index.html; try_files $uri $uri/ /index.html; # 支持Vue路由history模式 } location /api { proxy_pass http://localhost:8080; # 反向代理到后端 } } ``` --- ### **六、推荐学习资源** 1. **系统教程** - 书籍:《Spring Boot+Vue全栈开发实战》(王松著)[^1] - 视频:[尚硅谷SpringBoot2+Vue3整合实战](https://www.bilibili.com/video/BV1U44y1W77D) 2. **开源项目参考** - GitHub:[elunez/eladmin](https://github.com/elunez/eladmin)(权限管理系统) - Gitee:[SpringBoot-Vue-Quick](https://gitee.com/smallc/SpringBoot-Vue-Quick) 3. **脚手架工具** - [Spring Initializr](https://start.spring.io/) + [Vite](https://vitejs.dev/)(现代前端构建工具) --- ### **避坑指南** 1. 前后端分离session共享问题 → 用JWT替代Session 2. Vue路由刷新404 → Nginx配置`try_files` 3. 生产环境数据库配置 → 使用`application-prod.yml`隔离配置 > **学习建议**:从单表CRUD开始(如用户管理),逐步增加权限控制、文件上传、第三方登录等模块[^2][^4]。遇到问题时优先查阅[Spring官方文档](https://spring.io/)和[Vue官方文档](https://vuejs.org/)。 --- **附:技术栈全景图** ```mermaid graph LR A[前端] --> B[Vue3+TS] A --> C[Pinia状态管理] A --> D[Axios请求库] E[后端] --> F[SpringBoot3] E --> G[Spring Data JPA] E --> H[Spring Security] E --> I[MySQL/Redis] ``` --- ### 相关问题 1. SpringBoot如何整合Redis实现缓存功能? 2. Vue3中Pinia与Vuex的区别及适用场景? 3. 前后端分离项目如何解决跨域问题? 4. JWT认证在SpringBoot中的具体实现步骤? 5. 如何优化SpringBoot+Vue项目的首次加载速度?
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值