【问题标题】:How to send form data from React to express如何从 React 发送表单数据以表达
【发布时间】:2018-12-09 11:16:12
【问题描述】:

我是 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;

【问题讨论】:

    标签: javascript reactjs express


    【解决方案1】:

    您必须将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)
    })
    

    【讨论】:

      【解决方案2】:

      您尚未将数据发布到 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); })
      

      【讨论】:

        【解决方案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))
        }
        

        【讨论】:

          猜你喜欢
          • 2013-03-12
          • 1970-01-01
          • 2018-09-29
          • 2020-04-21
          • 2018-10-16
          • 2022-06-14
          • 2020-11-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多