英文:
Sending a POST to Spring endpoint giving status 400
问题
似乎在React应用程序中,从前端传递playerId参数到后端存在问题。Spring控制器中的createGame函数已设置为接收playerId参数,但是使用Axios从前端正确传递该值的问题尚未解决。已尝试使用Long和String作为playerId,但问题仍然存在。
仍然返回状态码400!
- 将其存储为String参数。
- 我使用了@PathVariable。
- 我尝试在Postman中直接写入参数。
- 我尝试更改端点。
- 另一个端点(/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 !
- Store it as a String parameter.
- I used @PathVariable.
- I tried to direct write the parameter in Postman.
- I tried change endpoint.
- 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("/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.");
}
}
And the React will be send like this:
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);
// 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<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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论