WebConfig.java 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. package com.svcman.config;
  2. import org.springframework.boot.web.server.ErrorPage;
  3. import org.springframework.boot.web.server.ErrorPageRegistrar;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.http.HttpStatus;
  7. import org.springframework.web.servlet.config.annotation.CorsRegistry;
  8. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  9. /**
  10. * Web 配置:CORS 支持 + SPA 路由转发
  11. */
  12. @Configuration
  13. public class WebConfig implements WebMvcConfigurer {
  14. @Override
  15. public void addCorsMappings(CorsRegistry registry) {
  16. registry.addMapping("/api/**")
  17. .allowedOrigins("*")
  18. .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
  19. .allowedHeaders("*");
  20. }
  21. /**
  22. * SPA 前端路由支持:
  23. * 所有非 /api 且非静态资源的 404 请求,回退到 index.html 由前端路由处理
  24. */
  25. @Bean
  26. public ErrorPageRegistrar spaErrorPageRegistrar() {
  27. return registry -> registry.addErrorPages(
  28. new ErrorPage(HttpStatus.NOT_FOUND, "/index.html")
  29. );
  30. }
  31. }