【问题标题】:Request method 'POST' not supported - spring boot不支持请求方法“POST”-spring boot
【发布时间】:2020-03-31 09:07:49
【问题描述】:

我尝试像这样POSTcurl -X POST -H "Content-Type: application/json" -d "{ \"fisrtName\":\"sunny\" , \"lastName\":\"leone\" }" http://localhost:8080/user

但我收到此错误:{"timestamp":"2019-12-06T11:07:17.196+0000","status":405,"error":"Method Not Allowed","message" :"不支持请求方法'POST'","path":"/user"}

但是,我有这样的休息控制器:

@PostMapping("/user/{firstName}/{lastName}")
    User addUser(@PathVariable String firstName,@PathVariable String lastName)
    {
        return userRepository.save(new User(firstName,lastName));
    }

如何解决?

【问题讨论】:

  • 好吧,看看你的 PostMapping。路径是什么?是您在 curl 请求中使用的 /user 吗?当您在 curl 请求中发送时,该方法是否需要 JSON 请求正文?
  • 我建议使用 Postman 之类的工具来使用 REST url,如果您刚开始,它会更容易理解。

标签: spring spring-boot


【解决方案1】:

您将 firstName 和 lastName 作为 JSON 传递。

但是你的映射说它们是路径变量:

@PostMapping("/user/{firstName}/{lastName}")

现在您尝试访问http://localhost:8080/user,但该路径没有映射。

您的帖子映射应该是:

@PostMapping("/user")
User addUser(@RequestBody User user){
    return userRepository.save(user);
}

【讨论】:

    【解决方案2】:

    我希望这会有所帮助。 如果您使用 @RequestBody 而不是 pathvariable 它会有所帮助。

    @PostMapping("/user)
        User addUser(@RequestBody User user)
        {
            if(user==null){
            return null;
            }else
            return userRepository.save(user);
        }
    
    curl --location --request POST "http://localhost:8080/user" \
      --header "Content-Type: application/json" \
      --data "{
      \"fisrtName\": \"sunny\",
      \"lastName\": \"leone\"
    }"
    

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 2016-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多