如何从React发送表格数据以表达

时间:2018-06-30 14:02:20

标签: javascript reactjs express

我在React中还很陌生。我正在尝试从发件人向我的后端发送注册数据。我尝试了传统方法,例如在表单中设置post方法和route,但这似乎不起作用。有没有一种方法可以将数据发送到后端,然后在前端接收该数据?

后端路由:路由为localhost:4000 / api / users / register

router.post("/register", (req, res) => {
    console.log(req.body)
    console.log('Hit')

      knex.select('*')
      .from('users')
      .where('email', req.body.email)
      .then(function(results) {          
            knex('users')
            .insert([{
              first_name: req.body.first_name,
              last_name: req.body.last_name,
              phone: req.body.phone,
              email: req.body.email,
              password: bcrypt.hashSync(req.body.password, 15)
            }])
            .returning('id')
            .then(function(id) {
              req.session.user_id = id;
            })
            .catch(function(error) {
              console.error(error)
            });
          }
      })
      .catch(function(error) {
        console.error(error)
      });
    // }
  });

反应表格代码:

class Register extends Component {
  constructor(props) {
    super(props)
    this.state = {
      first_name: '',
      last_name: '',
      email: '',
      password: '',
      phone: ''
    }
  }

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

  onSubmit = (e) => {
    e.preventDefault();
    // get form data out of state
    const { first_name, last_name, password, email, phone } = this.state;

    fetch('http://localhost:4000/api/users/register' , {
      method: "POST",
      headers: {
        'Content-type': 'application/json'
      }
      .then((result) => {
        console.log(result)
      })
  })
}
      render() {
        const { classes } = this.props;
        const { first_name, last_name, password, email, phone } = this.state;
        return (
          <div className="session">
          <h1>Create your Account</h1>
            <div className="register-form">
              <form method='POST' action='http://localhost:4000/api/users/register'>
                <TextField label="First Name" name="first_name" />
                <br/>
                <TextField label="Last Name" name="last_name" />
                <br/>
                <TextField label="Email" name="email" />
                <br/>
                <TextField label="Password" name="password" />
                <br/>    
                <TextField label="Phone #" name="phone" />
                <Button type='Submit' variant="contained" color="primary">
                  Register
                </Button>
              </form>
            </div>
          </div>
        );
      }
    }

    export default Register;

3 个答案:

答案 0 :(得分:3)

您尚未将数据发布到api。而且几乎没有编码错误。您需要来自

的更新代码
fetch('http://localhost:4000/api/users/register' , {
  method: "POST",
  headers: {
    'Content-type': 'application/json'
  }
  .then((result) => {
    console.log(result)
  })

收件人

fetch('http://localhost:4000/api/users/register' , {
  method: "POST",
  headers: {
    'Content-type': 'application/json'
  },
  body: JSON.stringify(this.state)
})
.then((result) => result.json())
.then((info) => { console.log(info); })

答案 1 :(得分:1)

您必须将audio.mp3中的数据发送到服务器,并且必须对来自state的响应使用json方法才能访问它。

fetch

答案 2 :(得分:0)

尝试使用名为axios的出色库。这就是低调的解释。

在前端,您将使用axios将数据发布到后端:

const reactData = [{ id: 1, name:' Tom'}, { id: 2, name:' Sarah'}];
const url = localhost:4000/api/users/register;

let sendData = () => {
axios.post(url, reactData)
   .then(res => console.log('Data send'))
   .catch(err => console.log(err.data))
}

在后端,只需执行以下操作即可接收该数据:

const url = localhost:4000/api/users/register;
const usersData= [];

let getData = () => {
axios.get(url)
   .then(res => usersData.push(res.data))
   .catch(err => console.log(err.data))
}