如何从React发送表单数据到Express

8

我在React方面还比较新。我想尝试通过表单提交将注册数据发送到后端。我已经尝试了传统的方法,例如在表单中设置post方法和路由,但似乎没有起作用。有没有一种方法可以将数据发送到后端,然后在前端接收该数据?

后端路由:路由为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)
      });
    // }
  });

React表单代码:

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个回答

6

您需要将state中的数据发送到服务器,并且需要使用fetch响应中的json方法来访问它。

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

5

您尚未将数据发布到API。此外,还存在一些编码错误。您需要更新代码从

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

To

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); })

3

尝试使用一个很酷的库,叫做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))
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接