node.js - how can I get form data from react to node.js?
问题描述
I am trying to send the form data of react component to the server through using axios or fetch. All of the code I wrote failed (in onSubmit). My server's port is 5000. I have already set bodyParser in server.js as well.
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));
// React Component
const Voting = ({ history }) => {
const [hasQuery, setQuery] = useState('');
const [formData, setFormData] = useState({
cat: false,
dog: false,
});
const { cat, dog } = formData;
const onChange = e => {
let obj = {};
obj[e.target.name] = e.target.checked;
setFormData(obj);
};
const onSubmit = async e => {
e.preventDefault();
1.
// axios.post('http://localhost:5000/main', { formData }).then(result => {
// console.log(result, 'result');
// });
2.
fetch('http://localhost:5000/main', {
method:'post',
body: formData
})
.then(res => res.json())
.then(data => alert(data.msg));
3.
// fetch('http://localhost:5000/main', {
// method: 'post',
// headers: {
// 'Content-Type': 'application/json; charset=utf-8'
// },
// body: JSON.stringify(formData),
// })
// .then(res => res.json())
// .then(obj => {
// if (obj.result === 'succ') {
// alert('Move on to the next.');
// }
// });
history.push(`/success`);
};
return (
<div>
<p>{hasQuery}</p>
<form
className='mode-container'
onSubmit={onSubmit}
mathod='POST'
action='http://localhost:5000/main'
>
<h3>Choose what you like more</h3>
<div>
<label>
cat
<input
type='radio'
name='cat'
value={cat}
onChange={onChange}
/>
</label>
<label>
dog
<input
type='radio'
name='dog'
value={dog}
onChange={onChange}
/>
</label>
</div>
<button type='submit'></button>
</form>
</div>
);
};
const mapStateToProps = state => ({
isAuthenticated: state.auth.isAuthenticated,
});
export default connect(mapStateToProps)(Voting);
And below is the code I wrote in node.js. req.body is an empty object.
// Node.js
mainRouter.post(
'/',
(req, _res, _next) => console.log(req, 'req.body'),
);
解决方案
您的目标/main
是所有客户端调用,但在服务器上您只有/
路由。
尝试以下操作:
axios.post('http://localhost:5000/', { formData }).then(result => {
console.log(result, 'result');
});
或者 - 更改服务器路由:
mainRouter.post(
'/main',
(req, _res, _next) => console.log(req, 'req.body'),
);
推荐阅读
- bokeh - 轴标签字体样式不改变散景
- python - “询问”异步 https 客户端:'SSLEOFERROR 尝试使用自签名证书连接到服务器--警告:手写堆栈跟踪--
- python - 我正在尝试从不同的目录读取 python 中文本文件的内容 - 找不到文件错误
- docker - 如何从 BYFN 中删除对等点和组织?
- parallel-processing - 金属非原子平行还原
- javascript - 如何在 WEB google App Script 上生成“id”?
- python-3.x - 我在添加带有设置 bin 的新列时出现错误 --TypeError: '<' 在 'int' 和 'str' 的实例之间不支持
- java - 如何将 POST 请求从 Android 发送到 PHP
- java - 测试覆盖率在 IntelliJ Idea 中不起作用
- python - 在 Ubuntu 上安装 CUDA + RAPIDS - “没有可用的内核映像”