【问题标题】:Data coming from frontend duplicates in backend twice来自前端的数据在后端重复两次
【发布时间】: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}。

任何人都可能知道为什么会发生这种情况,会很有帮助!

【问题讨论】:

    标签: node.js reactjs


    【解决方案1】:

    这很可能是因为您的按钮单击正在执行this.newUser,并且在您单击按钮时也触发了函数onSubmit

    我建议将onSubmit 留在表单标签中,并删除按钮中的onClick

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-11
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 2012-01-29
      • 2020-06-04
      • 2020-01-01
      • 1970-01-01
      相关资源
      最近更新 更多