Springboot配置CORS解决跨域后Postman请求返回空响应如何解决?
问题根因
你自定义的CORS过滤器doFilter方法完成响应头配置后,没有调用chain.doFilter(req, res)执行后续过滤器链和业务接口逻辑,请求直接在当前过滤器层终止,因此没有返回任何响应体内容。
浏览器跨域校验仅检查响应头的CORS字段合法性,因此会表现为跨域报错消失但接口返回空;Postman没有跨域校验逻辑,直接呈现为空响应。
修复方案
在doFilter方法末尾添加过滤器链调用逻辑即可,同时建议补充OPTIONS预检请求的特殊处理,避免预检请求执行不必要的业务逻辑,修改后代码如下:
@Component @Order(Ordered.HIGHEST_PRECEDENCE) public class MyConfiguration implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000"); response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, HEAD, OPTIONS, DELETE"); response.setHeader("Access-Control-Allow-Headers", "Accept, Accept-Language, Authorization, Cache-Control, Content-Language, Content-Type, X-Requested-With"); response.setHeader("Access-Control-Expose-Headers", "Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Origin, Cache-Control, Content-Language, Content-Length, Content-Type, Date, ETag, Expires, Last-Modified, Location, Pragma, Server, Transfer-Encoding, Vary, WWW-Authenticate"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Credentials", "true"); // 预检请求直接返回,不执行后续业务逻辑 if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { response.setStatus(HttpServletResponse.SC_OK); return; } // 执行后续过滤器和业务接口 chain.doFilter(req, res); } public void init(FilterConfig filterConfig) { } public void destroy() { } }
另外注意原代码中的doFilter方法没有声明抛出IOException和ServletException,调用chain.doFilter时需要补充异常声明,否则会编译报错。
更推荐的Spring Boot原生CORS配置方式
不需要自定义过滤器,直接通过Spring MVC提供的CORS配置即可,稳定性更高:
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://localhost:3000") .allowedMethods("POST", "PUT", "GET", "HEAD", "OPTIONS", "DELETE") .allowedHeaders("Accept", "Accept-Language", "Authorization", "Cache-Control", "Content-Language", "Content-Type", "X-Requested-With") .exposedHeaders("Accept-Ranges", "Access-Control-Allow-Credentials", "Access-Control-Allow-Origin", "Cache-Control", "Content-Language", "Content-Length", "Content-Type", "Date", "ETag", "Expires", "Last-Modified", "Location", "Pragma", "Server", "Transfer-Encoding", "Vary", "WWW-Authenticate") .maxAge(3600) .allowCredentials(true); } }
内容的提问来源于stack exchange,提问作者DigoStorm
相关产品推荐
相关产品推荐

