You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法向本地Spring应用发送GET以外请求,POST/PUT被识别为GET

问题分析与解决方案
  • 检查Spring控制器的请求映射
    确认你的Spring控制器中/endpoint端点使用的是@PostMapping(或@RequestMapping(method = RequestMethod.POST)),而非@GetMapping。如果控制器仅配置了GET请求的处理逻辑,POST请求会被默认处理为GET,就会出现你遇到的现象。

    正确的控制器示例代码:

    @RestController
    public class TestController {
        @PostMapping("/endpoint")
        public ResponseEntity<String> handlePostRequest(@RequestBody Map<String, Object> requestBody) {
            // 处理POST请求逻辑
            return ResponseEntity.ok("POST请求已处理");
        }
    }
    
  • 排查过滤器或安全框架的干扰
    部分Spring配置(比如Spring Security、自定义过滤器)可能会修改请求方法,或者触发重定向导致请求变为GET。

    • 如果使用Spring Security,可临时关闭CSRF验证测试:
      @Configuration
      public class SecurityConfig {
          @Bean
          public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
              http.csrf(csrf -> csrf.disable());
              return http.build();
          }
      }
      
    • 检查自定义过滤器,确保没有篡改请求方法的逻辑。
  • 配置CORS解决跨域问题
    若前端页面端口与Spring应用端口不同(比如前端在8081,后端在8080),会触发OPTIONS预检请求,若未配置CORS,可能导致请求异常。添加CORS配置:

    @Configuration
    public class CorsConfig {
        @Bean
        public CorsFilter corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(true);
            config.addAllowedOrigin("http://localhost:你的前端端口");
            config.addAllowedHeader("*");
            config.addAllowedMethod("*");
            source.registerCorsConfiguration("/**", config);
            return new CorsFilter(source);
        }
    }
    
  • 用浏览器开发者工具验证请求
    按下F12打开开发者工具,切换到「网络」标签,点击按钮发送请求后:

    • 确认请求方法确实是POST
    • 检查请求头里的Content-Type是否为application/json
    • 查看响应状态码,如果是3xx重定向,说明后端存在重定向逻辑导致请求转为GET

内容的提问来源于stack exchange,提问作者user23540567

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 09:25:12