Spring与Angular交互异常:请求返回HTML而非JSON数据
确认Security配置规则的优先级
Spring Security的规则是按配置顺序匹配的,必须把开放/users接口的规则放在所有认证拦截规则之前,否则会被后续的拦截规则覆盖。示例配置:@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/users").permitAll() // 先开放目标接口 .anyRequest().authenticated() // 再拦截其他请求 .and() .formLogin().disable() // 禁用默认表单登录,避免自动重定向到/login .httpBasic().disable(); }检查接口路径的匹配一致性
核对UserController的请求映射(比如@GetMapping("/users"))和Security配置里antMatchers的路径是否完全一致。如果项目配置了上下文路径(如server.servlet.context-path=/api),Security规则里必须加上前缀:antMatchers("/api/users").permitAll()验证跨域配置的完整性
跨域问题需同时保证Spring Security和Spring MVC的配置生效,示例配置:// Security中启用跨域 http.cors().configurationSource(corsConfigurationSource()); // 定义跨域规则Bean @Bean public CorsConfigurationSource corsConfigurationSource() { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(Arrays.asList("http://localhost:4200")); // Angular的运行地址 config.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS")); config.setAllowedHeaders(Arrays.asList("*")); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return source; }也可以在UserController上临时添加
@CrossOrigin注解,快速排除跨域因素。开启请求日志定位问题
在application.properties中添加日志配置,查看请求的完整处理流程:logging.level.org.springframework.security=DEBUG logging.level.org.springframework.web=DEBUG日志会显示请求匹配的Security规则、是否被拦截、重定向触发的具体原因,直接定位问题根源。
规范Postman的测试方式
使用Postman测试时,清除请求Cookie(或用无痕窗口),直接发送GET请求到http://localhost:8080/users,查看响应状态码和内容。如果仍出现重定向,说明问题完全在后端Security配置,与前端无关。排查自定义拦截器/过滤器
检查项目中是否存在自定义的HandlerInterceptor或Filter,这类组件可能在Security之前拦截请求,导致重定向或无响应。
内容的提问来源于stack exchange,提问作者GotaKev

