Reputation: 4472
I've already seen similar question with no success. I need to send a matrix of numbers from a web app (ReactJS) to a Spring Boot controller.
I've tried many combination but it always get error, my payload is:
{"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]]}
My react code is:
axios.post('http://localhost:8090/api/check', {
rows: this.props.rows
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
And my Spring Boot controller is:
@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;
}
I've already tried to declare @RequestParam(value = "rows[]")
or @RequestParam(value = "rows")
.
Rather than @RequestParam(value = "rows") final Object rows
.
But it always respond with error 400 (Bad request).
How can I pass a matrix through POST request?
Thanks
Upvotes: 1
Views: 4772
Reputation: 4472
Finally, I solved wrapping all the parameter in just one Object.
@JsonAutoDetect
public class Params {
private int[][] matrix;
private int row;
private int col;
private int num;
[...getters and setters]
And then declaring just one param in the sign of the method in the 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());
}
Crucial, the client should pass the object with its atrtibutes, without any kind of wrapper, so in this way:
axios.post('http://localhost:8090/api/check', {
matrix: this.props.rows,
"row": row - 1,
"col": col - 1,
"num": input.textContent
})
And not, in this way (with a root attribute "params"):
axios.post('http://localhost:8090/api/check', {
"params" : {
matrix: this.props.rows,
"row": row - 1,
"col": col - 1,
"num": input.textContent
}
})
Upvotes: 3
Reputation: 778
I would suggest to turn your variable "rows" into a int[][] array, cause thats it what your json represents.
Also, in my spring webapplication i don't neccesarly need to declare a request parameter by annotation. Try to remove the Annotation (Spring will detect the parameter itself). Also, remove all method parameter which are not included in the json (the request data).
@PostMapping(path = "/check")
@CrossOrigin(origins = "http://localhost:3000")
public boolean check(int[][] array) {
return true;
}
If you want to work with annotations, use @RequestBody for POST calls, @RequestParameter reads GET-Parameter (from URL like .../bla?param1rows=[[0,0]])
Upvotes: 0