CORS报错无法请求Heroku部署的Spring Boot应用,配置后仍未生效如何解决
问题描述
我尝试向部署在Heroku上的Spring Boot应用发送POST请求,前端代码如下:
const email = 'x@x.com'; const password = 'x'; const data = JSON.stringify({ email, password }); fetch( 'https://culinareat-test.herokuapp.com/api/user/users/_login', { method: 'POST', headers : { 'Accept' : 'application/json', 'Content-Type' : 'application/json' }, body : data, } ).then(res => { console.log(res); })
请求后得到的响应如下:
我的Spring Boot应用控制器代码如下:
@RestController @AllArgsConstructor public class UserController { private final UserService userService; @RequestMapping(method = RequestMethod.POST, value = "/user/users/_login") public LoginResponse logUserIn(@RequestBody LoginRequest loginRequest, HttpServletResponse response, HttpServletRequest request){ return userService.logUserIn(loginRequest, response, request); } // 其余接口 }
我参照Stack Overflow上的文章添加了如下CORS配置:
@Configuration public class AppConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedMethods("*"); } }
但配置后依然没有生效,还是无法正常发起请求。请问我应该如何处理?服务端还需要添加额外配置吗?
解决方案
- 完善CORS全局配置
你当前的CORS配置仅放开了请求方法限制,缺少请求源、请求头的放行配置,Spring Boot 2.4+版本建议使用如下完整配置:
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 生产环境建议替换为实际前端域名 .allowedOriginPatterns("*") .allowedMethods("*") .allowedHeaders("*") // 如果请求携带凭证(cookie、授权头、Session等)需要开启该配置 .allowCredentials(true) .maxAge(3600); } }
- 排查请求路径匹配问题
你前端请求的路径为/api/user/users/_login,但控制器接口配置的路径为/user/users/_login,请确认Spring Boot应用是否配置了server.servlet.context-path=/api,如果没有配置上下文路径,会导致接口404,响应缺失CORS头也会触发跨域报错。 - 集成Spring Security需额外配置CORS
Spring Security的请求拦截优先级高于WebMvc配置,需要在Security配置类中显式开启CORS支持:
@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http // 其余安全配置省略 .cors(Customizer.withDefaults()) .csrf().disable(); } }
- 确保预检OPTIONS请求不被拦截
跨域请求会先发送OPTIONS方法的预检请求,需要确保所有自定义拦截器、过滤器不会拦截OPTIONS请求,避免预检失败。 - 高优先级全局CORS过滤器方案
如果上述配置仍不生效,可以使用过滤器级别的CORS配置,优先级高于WebMvc配置:
@Component public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) response; res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT"); res.setHeader("Access-Control-Max-Age", "3600"); res.setHeader("Access-Control-Allow-Headers", "*"); res.setHeader("Access-Control-Allow-Credentials", "true"); if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) request).getMethod())) { res.setStatus(HttpServletResponse.SC_OK); return; } chain.doFilter(request, response); } }
内容的提问来源于stack exchange,提问作者Mhd Rizaldy Andrian Rambe
相关产品推荐
相关产品推荐

