前端与Java后端交互出现跨域问题的14种解决方案

06-01 1651阅读

跨域问题是前端与后端分离开发中的常见挑战,以下是14种完整的解决方案:

1 前端解决方案( 开发环境代理)

1.1 Webpack开发服务器代理

// vue.config.js 或 webpack.config.js
module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

1.2 Vite代理配置

// vite.config.js
export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
})

1.3 JSONP (仅限GET请求)

function jsonp(url, callback) {
  const script = document.createElement('script');
  script.src = `${url}?callback=${callback}`;
  document.body.appendChild(script);
}
// 后端需要返回类似 callbackName(data) 的响应

1.4 WebSocket

const socket = new WebSocket('ws://your-backend-url');

1.5 修改浏览器安全策略 (仅开发环境)

  • Chrome启动参数:--disable-web-security --user-data-dir=/tmp/chrome

    2 后端解决方案

    2.1 Spring框架解决方案

    2.1.1 使用@CrossOrigin注解

    @RestController
    @RequestMapping("/api")
    @CrossOrigin(origins = "*") // 允许所有来源
    public class MyController {
        // 控制器方法
    }

    2.1.2 全局CORS配置

    @Configuration
    public class WebConfig implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000", "http://example.com")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
        }
    }

    3.1.2 过滤器方式

    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:3000");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new FilterRegistrationBean(new CorsFilter(source));
    }

    2.2 Spring Boot特定配置

    2.2.1 application.properties配置

    # 允许的源
    cors.allowed-origins=http://localhost:3000,http://example.com
    # 允许的方法
    cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS
    # 允许的头部
    cors.allowed-headers=*
    # 是否允许凭证
    cors.allow-credentials=true
    # 预检请求缓存时间
    cors.max-age=3600

    2.3 Spring Security解决方案

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.cors().and()
                // 其他安全配置
                .csrf().disable(); // 通常需要禁用CSRF以简化API开发
        }
        
        @Bean
        CorsConfigurationSource corsConfigurationSource() {
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
            configuration.setAllowedMethods(Arrays.asList("GET","POST","PUT","DELETE","OPTIONS"));
            configuration.setAllowedHeaders(Arrays.asList("*"));
            configuration.setAllowCredentials(true);
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", configuration);
            return source;
        }
    }

    3 生产环境解决方案

    3.1 Nginx反向代理

    前端与Java后端交互出现跨域问题的14种解决方案
    (图片来源网络,侵删)
    server {
        listen 80;
        server_name yourdomain.com;
        
        location /api {
            proxy_pass http://backend-server: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;
        }
        
        location / {
            root /path/to/frontend/dist;
            try_files $uri $uri/ /index.html;
        }
    }

    4 高级方案

    4.1 基于Token的跨域认证

    // 后端添加响应头
    response.setHeader("Access-Control-Expose-Headers", "Authorization");
    response.setHeader("Authorization", "Bearer " + token);

    4.2 预检请求(OPTIONS)处理

    @RestController
    public class OptionsController {
        @RequestMapping(value = "/**", method = RequestMethod.OPTIONS)
        public ResponseEntity handleOptions() {
            return ResponseEntity.ok().build();
        }
    }

    4.3 动态允许源

    @Bean
    public CorsFilter corsFilter() {
        return new CorsFilter(new UrlBasedCorsConfigurationSource() {
            @Override
            public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
                CorsConfiguration config = new CorsConfiguration();
                String origin = request.getHeader("Origin");
                if (allowedOrigins.contains(origin)) { // 检查是否在允许列表中
                    config.addAllowedOrigin(origin);
                    config.setAllowedMethods(Arrays.asList("GET","POST","PUT","DELETE","OPTIONS"));
                    config.setAllowedHeaders(Arrays.asList("*"));
                    config.setAllowCredentials(true);
                }
                return config;
            }
        });
    }

    选择哪种解决方案取决于具体需求、安全要求和部署环境。生产环境中推荐使用Nginx反向代理或API网关方案,开发环境中可以使用代理或后端CORS配置。

    前端与Java后端交互出现跨域问题的14种解决方案
    (图片来源网络,侵删)
    前端与Java后端交互出现跨域问题的14种解决方案
    (图片来源网络,侵删)
免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们。

相关阅读

目录[+]

取消
微信二维码
微信二维码
支付宝二维码