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

发布于:2025-05-12 ⋅ 阅读:(13) ⋅ 点赞:(0)

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 {
    
        @Override
        public 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 {
    
        @Bean
        public 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,双重保障)。


网站公告

今日签到

点亮在社区的每一天
去签到