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

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

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的答案是正确的,但我将代码改写成了这样:

@PostMapping("/games")
public ResponseEntity<String> createGame(@RequestBody Map<String, Object> requestParams) {
    try {
        Long playerId = Long.parseLong(requestParams.get("playerId").toString());
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
        String gameCreated = now.format(formatter);
        Player player = playerRepository.findById(playerId).orElse(null);
        if (player == null) {
            return ResponseEntity.notFound().build();
        }
        Game game = new Game(gameCreated);
        gameRepository.save(game);
        GamePlayer gamePlayer = new GamePlayer(game, player);
        gamePlayerRepository.save(gamePlayer);
        return ResponseEntity.ok("Game created successfully!");
    } catch (Exception e) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to create game.");
    }
}

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

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

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

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

And the React will be send like this:

const handleClick = async () =&gt; {
    try {
      const response = await axios.post(`/api/games?playerId=${parseInt(storedPlayerId)}`);
      console.log(response.data);
    } catch (error) {
      console.log(error.response.data);
      // handle the error
    }
};

答案2

得分: 0

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

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

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

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

Spring的更改如下:

public ResponseEntity<String> createGame(@RequestBody PlayerRequest playerRequest) {
    Long playerId = playerRequest.getPlayerId();
    // 其他代码在这里
}

public class PlayerRequest {
    private Long playerId;

    public Long getPlayerId() {
        return playerId;
    }

    public void setPlayerId(Long playerId) {
        this.playerId = playerId;
}
英文:

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:

public ResponseEntity&lt;String&gt; createGame(@RequestBody PlayerRequest playerRequest) {
    Long playerId = playerRequest.getPlayerId();
    // other code goes here
}

public class PlayerRequest {
    private Long playerId;

    public Long getPlayerId() {
        return playerId;
    }

    public void setPlayerId(Long playerId) {
        this.playerId = playerId;
    }
}

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:

确定