我试图通过使用axios或fetch将react组件的表单数据发送到服务器。 我编写的所有代码都失败了(在onSubmit中)。 我的服务器的端口是5000。 我已经在server.js中设置了bodyParser。
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);
下面是我在node.js中编写的代码。 req.body是一个空对象。
// Node.js
mainRouter.post(
'/',
(req, _res, _next) => console.log(req, 'req.body'),
);
答案 0 :(得分:0)
您在所有客户通话中都以/main
为目标,但是在服务器上,您只有/
路由。
尝试以下操作:
axios.post('http://localhost:5000/', { formData }).then(result => {
console.log(result, 'result');
});
或者-更改服务器路由:
mainRouter.post(
'/main',
(req, _res, _next) => console.log(req, 'req.body'),
);