繁体   English   中英

如何使用ReactJS,Node.js和MySQL查询将数据从表单数据发送到数据库?

[英]How to send data from a form data to a database using ReactJS , Node.js and MySQL queries?

我目前使用表设置数据库,并且数据库已正确连接到节点服务器。 问题在于,它在执行时会将值存储为null或undefined,这使我觉得我没有从表单正确发送数据。

以下是我的Reactjs组件文件,其中包含表单和句柄函数

import React, {Component} from 'react';

class RegisterComponent extends React.Component {

  constructor() {
    super();

    this.state = {
      username: '',
      email:'',
      password:'',


      };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();


    const data = { username:this.state.username, email:this.state.email , password:this.state.password }

    fetch('/api/createAccount', { method: 'POST', 

    body: JSON.stringify(data), // data can be `string` or {object}!

    headers:{ 'Content-Type': 'application/json' } })

    .then(res => res.json())

    .catch(error => console.error('Error:', error))

    .then(response => console.log('Success:', response));
   }



  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label htmlFor="username">Enter username</label>
        <input id="username" name="username" type="text" />

        <label htmlFor="email">Enter your email</label>
        <input id="email" name="email" type="email" />

        <label htmlFor="password">Enter a password</label>
        <input id="password" name="password" type="text" />

        <button>Send data!</button>
      </form>
    );
  }
}

export default RegisterComponent;

以下是api请求脚本

app.post('/api/createAccount', function(req, res) {
    const username = req.body.username;
    const password = req.body.password;
    const email = req.body.email;



  con.query(`INSERT INTO usertest2 SET username = ? , email = ? , password = ? `, [username , email, password] ,  function(err, result) {

  console.log(username);
  if (err) throw err;
      res.send(' successfully');

    });


  });

您没有更改状态值的功能。 做类似的事情:

handleChange = (e) => {
  this.setState({
    [e.target.name]: e.target.value
  })
}

然后将所有输入添加到onChange

<input id="password" name="password" type="text" onChange={this.handleChange} />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM