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

myzjeezk  于 2023-03-22  发布在  React
关注(0)|答案(1)|浏览(148)

React app中的playerId参数从前端传递到后端似乎存在问题。Spring控制器中的createGame函数设置为接收playerId参数,但前端使用Axios没有正确传递该值。已尝试使用Long和String作为playerId,但是问题仍然存在。仍然得到状态400!
Spring
React
1.将其存储为String参数。
1.我使用了@PathVariable。
1.我试着直接在Postman中写参数。
1.我尝试更改端点。
1.另一个端点(/login),我没有显示工作良好,所以没有问题的代理。

nr9pn0ug

nr9pn0ug1#

在共享的React截图中-看起来像是你发送了一个JSON body。
但是,在Spring Controller中使用了- @RequestParam。
看起来你要么需要更改React部分以调用URL,如'/API/游戏/{playerId}'(因此playerId将作为URL的一部分传递),要么更新Spring Controller以接受@RequestBody(并创建一个带有字段'playerId'的类)-因此整个对象可以作为请求体传递。
目前React发送一个body -但Spring正在寻找一个URL查询参数。两个部分都需要做同样的事情-无论它是什么。
Spring的变化看起来像:

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;
    }
}

相关问题