繁体   English   中英

尝试使用 React 从 SpringBoot 获取时出现 400 错误请求

[英]400 Bad request when trying to fetch from SpringBoot using React

我尝试删除具有给定 ID 的实体。 但是,当我尝试从我的 API 中获取时,我收到 400 bad request 错误。

    async deleteFood(foodId) {
    const params = {
        'id' : foodId
    }

   const rawResponse = await fetch("food/delete", {
        method:"POST",
        headers: {'Content-Type': 'application/json'},
        body: params,
    });

   const content = await rawResponse.json();
}

在我的 SpringBoot 日志中,它显示缺少 id 参数:

WARN 7784 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MissingServletRequestParameterException: Required request parameter 'id' for method parameter type int is not present]

我已经尝试将参数放入 JSON.stringify(),但这并没有改变任何东西。

控制器代码:

@PostMapping(path = "/delete")
public @ResponseBody int deleteById(@RequestParam int id) {
    if (foodRepository.existsById(id)) {
        foodRepository.deleteById(id);
        return Response.SC_ACCEPTED;
    }
    return Response.SC_BAD_REQUEST;
}

您正在通过正文发送数据,但在控制器中您正在等待 @RequestParam

@PostMapping(path = "/delete")
public @ResponseBody int deleteById(@RequestParam int id) {
    if (foodRepository.existsById(id)) {
        foodRepository.deleteById(id);
        return Response.SC_ACCEPTED;
    }
    return Response.SC_BAD_REQUEST;
}

您需要更改接收 id 参数(@RequestBody 而不是@RequestParam)的方式,例如:

@PostMapping(path = "/delete")
public @ResponseBody int deleteById(@RequestBody int id) {
    if (foodRepository.existsById(id)) {
        foodRepository.deleteById(id);
        return Response.SC_ACCEPTED;
    }
    return Response.SC_BAD_REQUEST;
}

或更改您从 React 发送的方式(将其作为 url 参数发送)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM