【发布时间】:2020-11-10 19:10:20
【问题描述】:
class Signup extends React.Component {
constructor() {
super();
this.state = {
username: '',
email: '',
password: ''
}
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
}
onSubmit = (e) => {
e.preventDefault();
console.log(this.state);
this.newUser();
};
newUser = (e) => {
fetch("http://localhost:4000/signup", {
method: "POST",
headers: {
"Content-type": "application/json",
'Accept': 'application/json'
},
body: JSON.stringify(this.state)
})
.then((response) => response.json())
.then((result) => {
console.log(result);
});
}
render() {
return (
<div>
<form onSubmit={this.onSubmit}>
<input
onChange={this.onChange}
type="text"
name="username"
placeholder="Username"
/>
<input
onChange={this.onChange}
type="text"
name="email"
placeholder="Email"
/>
<input
onChange={this.onChange}
type="password"
name="password"
placeholder="Password"
/>
<button onClick={this.newUser}>Sign Up</button>
<p className="message">Do you have an account? <a href="login">Login</a></p>
</form>
</div>
)
}
}
Node.js
router.post('/signup', (req, res) => {
console.log(req.body)
});
我正在尝试使用 reactjs 和 nodejs 进行注册,但我在 nodejs 中获得的数据重复了两次。
我正在从前端发送我的用户名、电子邮件和密码的请求,在后端它重复。例如,我发送的数据在后端发送了两次。如果我要在后端 console.log(req.body) 中发送 {username: 'hello', email: hello@gmail.com, password: 2323} 它会发送两次 {username: 'hello', email: hello@gmail .com,密码:2323},{用户名:'hello',电子邮件:hello@gmail.com,密码:2323}。
任何人都可能知道为什么会发生这种情况,会很有帮助!
【问题讨论】: