代码之家  ›  专栏  ›  技术社区  ›  Alessandro

通过POST将数组从React应用程序发送到Spring Boot

  •  1
  • Alessandro  · 技术社区  · 7 年前

    我已经见过类似的问题,但没有成功。 我需要从一个web应用程序(ReactJS)向Spring引导控制器发送一个数字矩阵。

    我尝试了很多组合,但总是出错,我的有效载荷是:

    {"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]]}
    

    axios.post('http://localhost:8090/api/check', {
            rows: this.props.rows
        })
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
    

    @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(错误请求) .

    谢谢

    2 回复  |  直到 7 年前
        1
  •  3
  •   Alessandro    7 年前

    @JsonAutoDetect
    public class Params {
    
        private int[][] matrix;
        private int row;
        private int col;
        private int num;
    
        [...getters and setters]
    

        @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());
        }
    

    至关重要的是,客户机应该传递带有atritubutes的对象,而不使用任何包装器,因此以这种方式:

    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
         }
    })
    
        2
  •  0
  •   Sunchezz    7 年前

    我建议将变量“rows”转换为int[][]数组,因为这就是json所表示的。

    另外,在我的SpringWebApplication中,我不需要通过注释来声明请求参数。尝试删除注释(Spring将检测参数本身)。

    @PostMapping(path = "/check")
    @CrossOrigin(origins = "http://localhost:3000")
    public boolean check(int[][] array) {
        return true;
    }
    

    如果您想使用注释,请使用@RequestBody进行POST调用,@RequestParameter读取GET参数(从URL,如…/bla?param1rows=[[0,0]])