Spring Boot 2.3.3(无Spring Security)CORS跨域问题求助
Hey there, let's work through this CORS problem you're hitting with Spring Boot 2.3.3 and Angular. First, let's clarify why Postman works but your Angular app doesn't—this is super common!
Why Postman Works, But Angular Doesn't
Postman isn't bound by the browser's Same-Origin Policy, so it sends your request directly and gets the response without extra checks. But browsers automatically send a preflight OPTIONS request for cross-domain requests that aren't "simple" (like POSTs with custom headers, or non-GET/POST methods). If your Spring Boot server doesn't respond to this OPTIONS request with the right CORS headers, the browser blocks the actual response—hence that error about missing Access-Control-Allow-Origin.
Solutions to Fix the CORS Error
1. Quick Fix: Use @CrossOrigin for Individual Controllers/Methods
If you only need to enable CORS for a specific controller or endpoint, add the @CrossOrigin annotation:
// Allow requests from your Angular app's URL @CrossOrigin(origins = "http://localhost:4200") @RestController @RequestMapping("/api") public class YourController { @GetMapping("/data") public ResponseEntity<?> getData() { // Your logic here return ResponseEntity.ok("Success!"); } }
You can also use origins = "*" to allow all domains, but avoid this in production for security reasons.
2. Recommended: Global CORS Configuration
For a project-wide solution, create a configuration class that implements WebMvcConfigurer:
@Configuration public class GlobalCorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // Apply to all endpoints .allowedOrigins("http://localhost:4200") // Your Angular app's URL .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // Include OPTIONS for preflight .allowedHeaders("*") // Allow all request headers .allowCredentials(true); // Enable if you need to send cookies/auth tokens } }
⚠️ Note: If you use allowedOrigins = "*", you can't set allowCredentials = true—this is a browser security restriction, not a Spring Boot issue.
3. Alternative: CORS Filter
Another way to handle CORS globally is with a custom Filter. This is useful if you need more low-level control:
@Component public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; HttpServletRequest httpRequest = (HttpServletRequest) request; // Set CORS headers httpResponse.setHeader("Access-Control-Allow-Origin", "http://localhost:4200"); httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); httpResponse.setHeader("Access-Control-Allow-Headers", "*"); httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); // Handle preflight OPTIONS request directly if ("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) { httpResponse.setStatus(HttpServletResponse.SC_OK); return; } chain.doFilter(request, response); } }
Key Reminders
- Double-check that the
allowedOriginsvalue matches your Angular app's actual URL (e.g., if it's deployed to a production domain, update this accordingly). - Make sure your server is handling OPTIONS requests correctly—both the global config and filter above do this automatically, but if you have custom filters, ensure they don't block OPTIONS.
- For production, always specify exact allowed origins instead of using
*to prevent unauthorized cross-domain requests.
内容的提问来源于stack exchange,提问作者user10767069

