【问题标题】:Enable HTTP Request POST in Spring Boot在 Spring Boot 中启用 HTTP 请求 POST
【发布时间】:2025-11-26 09:50:02
【问题描述】:

我用的是Spring boot,这里是maven依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

对于网页,我将文件放在 src/main/resources/static 中。那里有我的 html 文件、js 库(angular、jquery)和 css 文件。

我正在尝试使用 Angular 进行 HTTP 请求 POST(我也有一个运行良好的 GET 请求)但我明白了

POST http://localhost:8080/xxxx/12/addEntry 405 (Method Not Allowed) 

在响应标头中

HTTP/1.1 405 Method Not Allowed
Server: Apache-Coyote/1.1
X-Application-Context: application
Allow: HEAD, GET
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 09 Jul 2014 13:04:05 GMT

我意识到在响应中允许没有 POST 方法。

控制器中的方法

@RequestMapping(value = "/xxxx/{uid}/addEntry", method = RequestMethod.POST)
@ResponseBody
public String createEntry(@PathVariable String uid, @RequestBody  String form) {
    System.out.println(form);
    return "index.html";
}

【问题讨论】:

  • 你确定 Spring 看到了控制器吗?该控制器的其他方法是否有效?
  • @axtavt 谢谢你的回答。 GET 请求正在运行。
  • 如果您尝试删除 @RequestBody String form 会怎样?
  • @axtavt 谢谢,现在 POST 请求正在运行。您的 cmets 帮助我意识到了这个问题。我没有在 POST 请求中发送 PAYLOAD。
  • 那你能回答你自己的问题吗?

标签: spring spring-mvc spring-boot


【解决方案1】:

有时尤其是在初始测试 Spring 的 csrf - 跨站点请求伪造 - 默认情况下会启动保护并阻止 POST 请求发生,临时解决方法是禁用 csrf。这通常在扩展 WebSecurityConfigurerAdapter 的 Web Security Config 类中完成

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable();
    }
}

注意:这在 Spring boot 版本 2.0.0.RC1 上有效,最好用作永久解决方法

【讨论】:

    【解决方案2】:

    另一种解决方案对我有用。我只需要向控制器本身添加适当的注释,如下所示:

    @RestController
    public class EntriesController {
        //your code here
    }
    

    【讨论】:

      【解决方案3】:

      这是不久前的事情,很抱歉当时没有发布答案,但我会尝试解释我认为发生了什么。

      我正在尝试使用 Chrome Postman 的插件测试 ajax 请求,但由于我遇到了 CORS 问题(我无法使用 POST 方法执行 ajax,因为服务器只允许我创建一个 HEAD,所以这是不可能的)或 GET 请求)。

      在同一台服务器上,我有 angular 应用程序(即必须发出 POST 请求的应用程序)和 Java API(即期待 POST 请求的应用程序),所以在那里,我没有CORS 问题。但它不起作用,因为我犯了另一个错误,即在 Angular 应用程序的 post 方法中,我没有在 POST 上发送有效负载数据。

      @RequestMapping(value = "/xxxx/{uid}/addEntry", method = RequestMethod.POST)
      @ResponseBody
      public String createEntry(@PathVariable String uid, @RequestBody  String form) {
          System.out.println(form);
          return "index.html";
      }
      

      我希望这能让答案更清楚。感谢阅读。

      【讨论】:

      • 对不起,这个答案没有解释任何东西。
      • @SergDerbst 对此感到抱歉,我希望这个解释对您有所帮助
      【解决方案4】:

      Spring Boot 默认开启 CSRF 安全性。通过 JS 提交表单数据时,您需要在 POST 到端点时包含 Spring Boot 生成的 _csrf 令牌。

      【讨论】:

        最近更新 更多