欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > 假如你的项目是springboot+vue怎么解决跨域问题

假如你的项目是springboot+vue怎么解决跨域问题

2025/5/13 19:24:31 来源:https://blog.csdn.net/qq_62112907/article/details/147875332  浏览:    关键词:假如你的项目是springboot+vue怎么解决跨域问题

1. 前端代理(开发环境推荐)

适用场景:Vue 开发环境调试时,避免直接请求后端接口的跨域问题。
实现步骤

  1. 在 Vue 项目的 vue.config.js 中配置代理:

    module.exports = {devServer: {proxy: {'/api': {  // 代理所有以 /api 开头的请求target: 'http://localhost:8080', // Spring Boot 后端地址changeOrigin: true, // 允许跨域pathRewrite: {'^/api': '' // 去除请求路径中的 /api 前缀}}}}
    }

    2.前端请求时使用 /api 前缀:

    axios.get('/api/users').then(response => {// 处理响应
    });

    优点:无需修改后端代码,适合开发阶段快速解决跨域。


2. 后端全局配置 CORS(生产环境推荐)

适用场景:生产环境需要后端直接支持跨域。
实现步骤

  1. 在 Spring Boot 中创建全局 CORS 配置类:

    @Configuration
    public class CorsConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**") // 所有接口.allowedOrigins("http://localhost:5173") // 允许的前端地址.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法.allowedHeaders("*") // 允许的请求头.allowCredentials(true) // 允许发送 Cookie.maxAge(3600); // 预检请求缓存时间(秒)}
    }

    2.若使用 Spring Security,需额外放行 OPTIONS 请求(预检请求):

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.cors() // 启用 CORS.and()// 其他安全配置....authorizeRequests().requestMatchers(HttpMethod.OPTIONS).permitAll() // 放行 OPTIONS 请求.anyRequest().authenticated();return http.build();}
    }

3. 后端注解配置(按接口控制)

适用场景:仅特定接口需要跨域支持。
实现步骤:在 Controller 或方法上添加 @CrossOrigin 注解:

@RestController
@CrossOrigin(origins = "http://localhost:5173") // 类级别注解
public class UserController {@GetMapping("/users")@CrossOrigin(origins = "http://localhost:5173") // 方法级别注解public List<User> getUsers() {// 业务逻辑}
}

4. Nginx 反向代理(生产环境终极方案)

适用场景:前后端部署到同一域名下,彻底避免跨域。
实现步骤

  1. 配置 Nginx,将前端请求代理到后端接口:

    server {listen 80;server_name your-domain.com;# 前端静态资源location / {root /path/to/vue/dist;index index.html;try_files $uri $uri/ /index.html;}# 后端 API 代理location /api {proxy_pass http://localhost:8080;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}
    }

    2.重启 Nginx:

    sudo nginx -s reload

总结

方案适用场景优点缺点
前端代理开发环境无需后端改动,快速解决跨域仅适用于开发环境
后端全局 CORS生产环境统一管理,安全性可控需后端配置
注解配置特定接口跨域灵活控制单个接口配置冗余,维护成本高
Nginx 反向代理生产环境部署彻底解决跨域,提升性能需运维支持

推荐组合

  • 开发环境:前端代理(方案1) + 后端全局 CORS(方案2)。

  • 生产环境:Nginx 反向代理(方案4) + 后端全局 CORS(方案2,双重保障)。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词