首页 > 解决方案 > 使用 Express API 的 React 表单返回无法 POST /

问题描述

当使用 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 上运行。错误地将项目连接在一起可能是问题所在。路由是另一种可能性。

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

标签: reactjsexpress

解决方案


您的代码将使页面刷新,您将失去应用程序的状态,这不是 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);}

推荐阅读