Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send form data from React to express

i'm fairly new in React. I'm trying to send register data to my backend from a from submit. I've tried the traditional method like setting post method and route in the form but that doesn't seem to work. Is there a way to send the data to back end then receive that data on the front end?

back end route: route is 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 form code:

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;
like image 585
itstman Avatar asked Jun 30 '18 14:06

itstman


People also ask

How do I send form data to an email in React?

Go to the 'Email Template' tab on the side menu and click on the 'Create New Template' button. For testing purposes, we will use this default one. A caveat, the variables in double curly brackets are dynamic variables that will be replaced with the data we'll provide in the method emailjs. send , in our case, in React.


2 Answers

You have to send the data in your state to the server, and you have to use the json method on the response from fetch in order to access it.

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)
})
like image 178
Tholle Avatar answered Sep 21 '22 09:09

Tholle


You have not posted the data to the api. Also there are few coding errors. You need update code from

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); })
like image 20
Saurabh Ghewari Avatar answered Sep 18 '22 09:09

Saurabh Ghewari