reactjs - 使用 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)
解决方案
您的代码将使页面刷新,您将失去应用程序的状态,这不是 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);}
推荐阅读
- html - 检测格式错误的 html 字符串并将其转换为 jQuery 对象
- python - 如何删除熊猫中的图例
- bash - 从 BASH 脚本安装 npm 无法正常工作
- amazon-web-services - AWS Cognito 软件令牌 MFA 工作一次,然后意外恢复为 SMS MFA 以供将来所有登录
- python - OpenCV 函数不会在 Pycharm 中运行,但在 Jupyter 中没有问题
- php - 如何删除php数组中字符串的结尾?
- python - 使用 Conda 安装的软件包,但 ModuleNotFoundError
- windows - 如何在 Windows 上使用 AWS-RunPowerShellScript 运行包含空格的命令?
- java - 创建目录树(Java、Windows)
- javascript - javascript获取选择选项值和隐藏文本字段值以进行计算