1 Front-end solution (development environment agent)
1.1 Webpack Development Server Agent
// or = { devServer: { proxy: { '/api': { target: 'http://localhost:8080', changeOrigin: true, pathRewrite: { '^/api': '' } } } } }
1.2 Vite proxy configuration
// export default defineConfig({ server: { proxy: { '/api': { target: 'http://localhost:8080', changeOrigin: true, rewrite: (path) => (/^\/api/, '') } } } })
1.3 JSONP (GET request only)
function jsonp(url, callback) { const script = ('script'); = `${url}?callback=${callback}`; (script); } // The backend needs to return a response similar to callbackName(data)
1.4 WebSocket
const socket = new WebSocket('ws://your-backend-url');
1.5 Modify browser security policy (development environment only)
Chrome startup parameters: --disable-web-security --user-data-dir=/tmp/chrome
2 Backend Solutions
2.1 Spring Framework Solution
2.1.1 Use @CrossOrigin annotation
@RestController @RequestMapping("/api") @CrossOrigin(origins = "*") // All sources are allowedpublic class MyController { // Controller method}
2.1.2 Global CORS configuration
@Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { ("/**") .allowedOrigins("http://localhost:3000", "") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); } }
2.1.3 Filter method
@Bean public FilterRegistrationBean<CorsFilter> corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); (true); ("http://localhost:3000"); ("*"); ("*"); ("/**", config); return new FilterRegistrationBean<>(new CorsFilter(source)); }
2.2 Spring Boot Specific Configuration
Configuration
# Allowed Source-origins=http://localhost:3000, # Allowed methods-methods=GET,POST,PUT,DELETE,OPTIONS # Allowed head-headers=* # Whether to allow credentials-credentials=true # Preflight request cache time-age=3600
2.3 Spring Security Solution
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { ().and() // Other security configurations .csrf().disable(); // CSRF is usually required to simplify API development } @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); (("http://localhost:3000")); (("GET","POST","PUT","DELETE","OPTIONS")); (("*")); (true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); ("/**", configuration); return source; } }
3 Production environment solutions
Nginx reverse proxy
server { listen 80; server_name ; 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/ /; } }
4 Advanced Solutions
4.1 Cross-domain authentication based on token
// Add response header to the backend("Access-Control-Expose-Headers", "Authorization"); ("Authorization", "Bearer " + token);
4.2 Pre-flight request (OPTIONS) processing
@RestController public class OptionsController { @RequestMapping(value = "/**", method = ) public ResponseEntity<?> handleOptions() { return ().build(); } }
4.3 Dynamic Allowed Source
@Bean public CorsFilter corsFilter() { return new CorsFilter(new UrlBasedCorsConfigurationSource() { @Override public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { CorsConfiguration config = new CorsConfiguration(); String origin = ("Origin"); if ((origin)) { // Check if it is in the allowed list (origin); (("GET","POST","PUT","DELETE","OPTIONS")); (("*")); (true); } return config; } }); }
Which solution to choose depends on the specific requirements, security requirements, and deployment environment. It is recommended to use Nginx reverse proxy or API gateway solution in production environments, and can use proxy or backend CORS configuration in development environments.
The above is the detailed content of 14 solutions for cross-domain problems when interacting with Java and the front-end. For more information on solving cross-domain problems in Java, please pay attention to my other related articles!