Redux动作req.body未定义为快速路线

时间:2017-10-11 12:38:57

标签: node.js reactjs express react-redux redux-form

我一直在努力使用这个功能,它应该将redux-form值发送到我的快速服务器并等待mongoose模型。

请求正文一旦到达快速路线,就不包含我在redux-action中发送的表单值。表单值在客户端(在submitInvestment操作内)中是正确的console.logged。虽然,一旦发送表达(使用axios) - >控制台记录req.body显示 undefined

form.js

<form onSubmit={this.props.handleSubmit((values) => { this.props.submitInvestment(values) })}>

export default connect(null, actions)(reduxForm({ form: 'investmentForm' })(InvestmentForm))

actions.js

export const submitInvestment = (values) => async dispatch => {
  console.log('before request')
  console.log(values)
  const res = await axios.post('/api/investments', values);
  console.log('after request', res.data)
  // dispatch({ type: FETCH_USER, payload: res.data });
};

route.js

module.exports = app => {
  app.post('/api/investments', async (req, res) => {
    console.log(req.body)
    res.sendStatus(200);
  });
}

on form submission (console.log browser)

+ server logs an undefined req.body

此外;当我尝试使用完全构建的route.js

捕获请求时
module.exports = app => {
  app.post('/api/investments', async (req, res) => {
    const { currency, units, date } = req.body;

    const investment = new Investment({ 
      currency,
      units,
      date,
      _user: req.user.id
    });

    try {
      await investment.save();
      res.status(200);
    } catch (err) {
      res.status(422).send(err);
    }
  });
}

然后我的服务器日志

[0] (node:25154) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot match against 'undefined' or 'null'.
[0] (node:25154) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

1 个答案:

答案 0 :(得分:0)

传入请求需要由body parser中间件

处理

App.js

app.use(bodyParser.json());