向Spring端点发送POST请求,返回状态码400。

huangapple go评论127阅读模式
英文:

Sending a POST to Spring endpoint giving status 400

问题

似乎在React应用程序中,从前端传递playerId参数到后端存在问题。Spring控制器中的createGame函数已设置为接收playerId参数,但是使用Axios从前端正确传递该值的问题尚未解决。已尝试使用Long和String作为playerId,但问题仍然存在。
仍然返回状态码400!

Spring

React

  1. 将其存储为String参数。
  2. 我使用了@PathVariable。
  3. 我尝试在Postman中直接写入参数。
  4. 我尝试更改端点。
  5. 另一个端点(/login)正常工作,所以代理没有问题。
英文:

It appears that there is an issue passing the playerId parameter from the frontend to the backend in a React app. The createGame function in the Spring controller is set up to receive a playerId parameter, but the value is not being properly passed from the frontend using Axios. It has been attempted to use a Long and a String for the playerId, but the issue persists.
Still getting status 400 !

Spring

React

  1. Store it as a String parameter.
  2. I used @PathVariable.
  3. I tried to direct write the parameter in Postman.
  4. I tried change endpoint.
  5. Another endpoint (/login) which i'm not showing works good so no problem with proxy.

答案1

得分: 1

Daniel的答案是正确的,但我将代码改写成了这样:

  1. @PostMapping("/games")
  2. public ResponseEntity<String> createGame(@RequestBody Map<String, Object> requestParams) {
  3. try {
  4. Long playerId = Long.parseLong(requestParams.get("playerId").toString());
  5. LocalDateTime now = LocalDateTime.now();
  6. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
  7. String gameCreated = now.format(formatter);
  8. Player player = playerRepository.findById(playerId).orElse(null);
  9. if (player == null) {
  10. return ResponseEntity.notFound().build();
  11. }
  12. Game game = new Game(gameCreated);
  13. gameRepository.save(game);
  14. GamePlayer gamePlayer = new GamePlayer(game, player);
  15. gamePlayerRepository.save(gamePlayer);
  16. return ResponseEntity.ok("Game created successfully!");
  17. } catch (Exception e) {
  18. return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to create game.");
  19. }
  20. }

而React部分将会发送如下请求:

  1. const handleClick = async () => {
  2. try {
  3. const response = await axios.post(`/api/games?playerId=${parseInt(storedPlayerId)}`);
  4. console.log(response.data);
  5. } catch (error) {
  6. console.log(error.response.data);
  7. // 处理错误
  8. }
  9. };
英文:

Daniel's answer is correct but I overwrite the code like this:

  1. @PostMapping(&quot;/games&quot;)
  2. public ResponseEntity&lt;String&gt; createGame(@RequestBody Map&lt;String, Object&gt; requestParams) {
  3. try {
  4. Long playerId = Long.parseLong(requestParams.get(&quot;playerId&quot;).toString());
  5. LocalDateTime now = LocalDateTime.now();
  6. DateTimeFormatter formatter = DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd&#39;T&#39;HH:mm:ss&quot;);
  7. String gameCreated = now.format(formatter);
  8. Player player = playerRepository.findById(playerId).orElse(null);
  9. if (player == null) {
  10. return ResponseEntity.notFound().build();
  11. }
  12. Game game = new Game(gameCreated);
  13. gameRepository.save(game);
  14. GamePlayer gamePlayer = new GamePlayer(game, player);
  15. gamePlayerRepository.save(gamePlayer);
  16. return ResponseEntity.ok(&quot;Game created successfully!&quot;);
  17. } catch (Exception e) {
  18. return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(&quot;Failed to create game.&quot;);
  19. }
  20. }

And the React will be send like this:

  1. const handleClick = async () =&gt; {
  2. try {
  3. const response = await axios.post(`/api/games?playerId=${parseInt(storedPlayerId)}`);
  4. console.log(response.data);
  5. } catch (error) {
  6. console.log(error.response.data);
  7. // handle the error
  8. }
  9. };

答案2

得分: 0

在共享的React截图中,看起来你发送了一个JSON主体。

然而,在Spring Controller中使用了@RequestParam。

看起来你需要改变React部分,调用URL类似'/api/games/{playerId}'(这样playerId将作为URL的一部分传递),或者更新Spring Controller以接受@RequestBody(并创建一个带有字段'playerId'的类)- 这样整个对象可以作为请求主体传递。

因为当前React发送了一个主体,但Spring正在寻找一个URL查询参数。两个部分需要做同样的事情-无论是什么。

Spring的更改如下:

  1. public ResponseEntity<String> createGame(@RequestBody PlayerRequest playerRequest) {
  2. Long playerId = playerRequest.getPlayerId();
  3. // 其他代码在这里
  4. }
  5. public class PlayerRequest {
  6. private Long playerId;
  7. public Long getPlayerId() {
  8. return playerId;
  9. }
  10. public void setPlayerId(Long playerId) {
  11. this.playerId = playerId;
  12. }
英文:

In shared React screenshot - it looks like you send a JSON body.

However, in Spring Controller - @RequestParam is used.

It looks like you either need to change React part to call URL like '/api/games/{playerId}' (so playerId would be passed as part of URL) or update Spring Controller to accept @RequestBody (and create a class with field 'playerId') - so whole object could be passed as request body.

As currently React sends a body - but Spring is looking for a URL query param. Both parts need to do same thing - whatever it will be.

Spring changes would look like:

  1. public ResponseEntity&lt;String&gt; createGame(@RequestBody PlayerRequest playerRequest) {
  2. Long playerId = playerRequest.getPlayerId();
  3. // other code goes here
  4. }
  5. public class PlayerRequest {
  6. private Long playerId;
  7. public Long getPlayerId() {
  8. return playerId;
  9. }
  10. public void setPlayerId(Long playerId) {
  11. this.playerId = playerId;
  12. }
  13. }

huangapple
  • 本文由 发表于 2023年3月22日 05:09:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75806376.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定