生产环境Vue.js+Spring Boot的CORS(代理)问题解决方案咨询
生产环境Vue+Spring Boot请求转发与跨域问题解决
针对开发阶段用devServer代理/api到后端,生产构建后请求路径错误及CORS问题,提供三种可行方案:
方案1:后端Spring Boot全局配置CORS
直接在后端开启跨域支持,让前端可直接请求后端地址,无需代理。
创建CORS全局配置类:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration public class CorsConfig { @Bean public CorsFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); // 生产环境建议替换为前端实际部署域名,如"https://your-frontend.com" config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }
前端修改请求基础地址(以axios为例):
// 生产环境直接指向后端服务地址 axios.defaults.baseURL = 'http://localhost:8087/'
之后前端请求/login、/register会直接发送到http://localhost:8087/login、http://localhost:8087/register,同时解决CORS问题。
方案2:Nginx反向代理(推荐生产环境使用)
通过Nginx统一管理前端静态资源和请求转发,实现同域名下的请求转发,避免跨域。
Nginx配置示例:
server { listen 80; server_name your-frontend-domain.com; # 指向Vue构建后的dist目录 root /usr/share/nginx/html; index index.html; # 转发/api开头的请求到后端 location /api { proxy_pass http://localhost:8087/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; # 重写路径,移除/api前缀 rewrite ^/api/(.*)$ /$1 break; } # 处理Vue路由刷新404问题 location / { try_files $uri $uri/ /index.html; } }
此方案下前端无需修改任何请求路径,保持开发时的/api/login写法即可,Nginx会自动转发到后端对应接口,且因前端与Nginx同域名,不存在CORS问题。
方案3:Vue环境变量区分配置
通过Vue的环境变量,自动切换开发/生产环境的请求基础地址。
- 在项目根目录创建
.env.development文件:
VUE_APP_BASE_URL = '/api'
- 创建
.env.production文件:
VUE_APP_BASE_URL = 'http://localhost:8087/'
- 在axios配置中引入环境变量:
axios.defaults.baseURL = process.env.VUE_APP_BASE_URL
开发时使用devServer代理/api,生产时直接请求后端地址,配合后端CORS配置即可解决问题。
内容的提问来源于stack exchange,提问作者Emre
相关产品推荐
相关产品推荐

