我已经看到类似的问题但没有成功。 我需要将数字矩阵从 Web 应用程序 (ReactJS) 发送到 Spring Boot Controller 。
我尝试了很多组合,但总是出错,我的有效载荷是:
{"rows":[[7,0,0,6,4,0,0,0,0],[9,4,0,0,0,0,8,0,0],[0,8,6,2,5,0,0,9,0],[0,0,0,0,6,8,7,3,0],[4,0,8,0,2,1,0,0,0],[0,0,3,0,0,0,1,6,4],[0,0,0,0,0,9,6,7,5],[3,9,0,0,8,5,0,1,2],[0,0,5,0,0,4,0,0,0]]}
我的 react 代码是:
axios.post('http://localhost:8090/api/check', {
rows: this.props.rows
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
我的 Spring Boot Controller 是:
@PostMapping(path = "/check")
@CrossOrigin(origins = "http://localhost:3000")
public boolean check(@RequestParam(value = "rows") final int[] array, final int row, final int col, final int num) {
return true;
}
我已经尝试声明 @RequestParam(value = "rows[]")
或 @RequestParam(value = "rows")
。
而不是 @RequestParam(value = "rows") final Object rows
。
但它总是以错误 400(错误请求) 响应。
如何通过 POST 请求传递矩阵?
谢谢
最佳答案
最后,我解决了将所有参数包装在一个对象中的问题。
@JsonAutoDetect
public class Params {
private int[][] matrix;
private int row;
private int col;
private int num;
[...getters and setters]
然后在 Controller 中的方法的符号中只声明一个参数:
@PostMapping(path = "/check")
@CrossOrigin(origins = "http://localhost:3000")
public boolean check(@RequestBody final Params params) {
return sudokuGenerator.checkValue(params.getMatrix(), params.getRow(), params.getCol(), params.getNum());
}
至关重要的是,客户端应该传递带有属性的对象,没有任何类型的包装器,因此以这种方式:
axios.post('http://localhost:8090/api/check', {
matrix: this.props.rows,
"row": row - 1,
"col": col - 1,
"num": input.textContent
})
而不是,以这种方式(使用根属性“params”):
axios.post('http://localhost:8090/api/check', {
"params" : {
matrix: this.props.rows,
"row": row - 1,
"col": col - 1,
"num": input.textContent
}
})
关于java - 通过 POST 从 React App 发送数组到 Spring Boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52990938/