将JS数组作为列表传递给Spring MVC控制器

问题描述 投票:0回答:2

我正在使用ReactJs开发Web应用程序的前端。在这里,我进行了传递对象数组的API POST。

这些对象是在事件处理程序中创建的,如下所示:

eventHandler(id1, id2, e) {
    let payload = this.state.payload;
    let changedItem= {
        changeTo: e,
        id1: id1,
        id2: id2
    };

    let res = [];
    payload.forEach(item=> {
        if (item.id1 !== id1
            || item.id2 !== id2) {
            res.push(control);
        }
    });
    res.push(changedItem);

    this.setState({
        payload: res
    });
}

我已经通过在此之后打印阵列来验证了此功能。接下来,我进行POST调用,并传入数组:

onClick() {

    let changedControls = (this.state.payload);

    updateControls(changedControls).then(() => {
        this.setState({
            payload: []
        });
    }).catch((error) => {
         console.log(error);
    })
}

API调用在单独的文件中定义为:

export const updateControls = (changedControls) => {
let uri = '/api/update-controls';
return new Promise((resolve, reject) => {
    axios.post(uri, changedControls).then(response => {
        if (response != null) {
            resolve(response.data)
        }
    }).catch(err => {
        console.log(err.response.data);
    })
})

};

理想情况下,下一步是调用我的Java控制器,定义为:

@RequestMapping(value = "/update-controls", method = RequestMethod.POST)
public void updateControls(@RequestParam(value = "updatedControls") List<ControlsUpdate> updatedControls) throws Exception {
    initServiceClientRest();
    String user = getUserId();

    ResponseEntity responseEntity = serviceClientRest.update(updatedControls, user);

    if (responseEntity != null) {
        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throwErrorMessages(responseEntity);
        }
    }
}

我相信这就是错误所在。我收到一个400错误,说:必需的列表参数'updatedControls'不存在'。

有什么建议吗?

编辑:很抱歉API POST调用中的错字!但这不是问题,只是我在复制代码时所做的错字]

java reactjs spring post model-view-controller
2个回答
0
投票

存在拼写错误:

export const updateControls = (changedControls) => {
let uri = '/api/update-controls';
return new Promise((resolve, reject) => {
    axios.post(uri, changedControls).then(response => { // Here you were passing updatedControls
        if (response != null) {
            resolve(response.data)
        }
    }).catch(err => {
        console.log(err.response.data);
    })
})
};

0
投票
axios.post(uri, changedControls).then(response => {

代替

axios.post(uri, updatedControls).then(response => {

0
投票

[您要将数组作为http正文发送,对吗?您必须使用@RequestBody而不是@RequestParam

public void updateControls(@RequestBody(value = "updatedControls") List<ControlsUpdate> updatedControls) throws Exception {...}

@RequestParam用于URL参数

© www.soinside.com 2019 - 2024. All rights reserved.