Home  >  Article  >  Backend Development  >  Send POST to Spring endpoint giving status 400

Send POST to Spring endpoint giving status 400

王林
王林forward
2024-02-13 16:10:06793browse

向 Spring 端点发送 POST,给出状态 400

Question content

There seems to be an issue with passing the playerId parameter from the frontend to the backend in a React application. The createGame function in the Spring controller is set up to receive the playerId parameter, but the value is not passed correctly from the frontend using Axios. Tried using long and string as playerId but the problem persists. Still got status 400!

spring

reaction

  1. Store it as a string parameter.
  2. I used @PathVariable.
  3. I tried writing the parameters directly in Postman.
  4. I tried changing the endpoint.
  5. The other endpoint (/login) that I didn't show is working fine, so there is no problem with the proxy.

Workaround

In the shared react screenshot - it looks like you are sending a json body.

But, in spring controller - use @requestparam.

Looks like you either need to change the react part to call a url like '/api/games/{playerid}' (so the playerid will be passed as part of the url) or update the spring controller to accept @requestbody (and create a class with a field "playerid") - so the entire object can be passed as the request body.

Currently react sends a body - but spring is looking for url query parameters. Both parts need to do the same thing - whatever it is.

The changes in spring are as follows:

public ResponseEntity<String> 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;
    }
}

The above is the detailed content of Send POST to Spring endpoint giving status 400. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete