使用Express API的React表单返回无法POST /

时间:2018-11-29 20:59:38

标签: reactjs express

当将pug用作Express.js的视图引擎时,我能够使用表单。但是当我尝试使用React时,我无法使表单处理正常工作。

// Component.js
  </React.Fragment>
         // API_POST_URL=http://localhost:4000/api/donate
      <form action={process.env.API_POST_URL} method='post' id='testForm'> 
        <input type="hidden" name='step' value='3' />
        <button type='submit'>Post Test form</button>
      </form>
  </React.Fragment>

// index.js in another project folder
router.post('/api/donate', (req, res, next) => {

 // code testing for earlier steps removed

 else if (req.body.step === '3') {
      res.json({ message : "here's a response back"});
  }
});

前端在端口3000上运行,后端在端口4000上运行。将项目错误地连接在一起可能是问题所在。路由是另一种可能性。

我已经能够使用对以上(http://localhost:4000/api/donate)的ENV变量URL的邮递员请求接收响应对象

1 个答案:

答案 0 :(得分:1)

您的代码将刷新页面,并且您将松开应用程序的状态,而这不是SPA的目标。

您可以这样:

</React.Fragment>
  <form onSubmit={submitFormHandler()}> 
    <input type="hidden" name='step' value='3' />
    <button type='submit'>Post Test form</button>
  </form>

将以上字段存储为组件状态,并将其传递给submitFormHandler()

使用axios通过http提交表单。

submitFormHandler = (data) => { axios.post('http://localhost:4000/api/donate',data);}