Axios-Redux对Express端点的反应 - 触发了.then和.catch

问题描述 投票:1回答:1

我正在使用Redux表单向Express端点发送POST调用。端点应该返回成功保存的对象或错误。

端点成功保存发布的数据并返回JSON。但是Redux动作中的Axios选择.then和.catch触发器 - 在以下操作中,它记录以下内容:

successful response:  { …}
failure response:  undefined

我究竟做错了什么?

我的价值观:

export function addPlot(props) {
    const user = JSON.parse(localStorage.getItem('user'));
    return function(dispatch) {
        axios
            .post(
                `${ROOT_URL}/plots`,
                {
                    props
                },
                { headers: { authorization: user.token } }
            )
            .then(response => {
                console.log('successful response: ', response.data);
                const plotModal = document.getElementById('plotModal');
                plotModal.modal('dispose');
                dispatch({ type: PLOT_ADDED, payload: response.data });
                dispatch({ type: ADDING_PLOT, payload: false });
                dispatch({
                    type: NEW_PLOT_GEOJSON,
                    payload: ''
                });
            })
            .catch(response => {
                console.log('failure response: ', response.data);
                dispatch(authError(PLOT_ADD_FAILURE, 'Failed to add plot'));
            });
    }

我的终点:

exports.newPlot = async (req, res, next) => {
    console.log(JSON.stringify(req.body.props));
    let company;
    if (req.user.companyCode !== 'Trellis') {
        company = req.user.companyCode;
    } else {
        company = req.body.props.company;
    }
    const {
        name,
        feature,
        growerPhone,
        plotCode,
        rootStock,
        region,
        variety,
        grower,
        planted
    } = req.body.props;
    const plot = new Plot({
        name,
        grower,
        variety,
        planted,
        region,
        rootStock,
        plotCode,
        growerPhone,
        feature,
        company
    });
    try {
        const newPlot = await plot.save();
        res.json(newPlot);
    } catch (e) {
        console.log("couldn't save new plot", JSON.stringify(e));
        return res.status(422).send({ error: { message: e, resend: true } });
    }
};
reactjs express redux axios
1个回答
1
投票

您可以使用redux-thunk中间件来管理异步操作。

我看到的问题是你没有调度axios动作,你必须调用dispatch(this.props.addPlot(props))in命令在redux存储中执行某些操作。

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