How to Send Data from React to Node js Express + MySQL

How to Send Data from React to Node js Express + MySQL

React js pass form data to node js express app; This tutorial will guide you on how to send or pass form data from react js app to node js express app and store it on MySQL database using fetch().

This tutorial will create a simple form in react js app and send the data of this form to node js express app. Also, the data will be saved in the MySQL database.

In react js app it is very easy to call the node js app rest APIs. In this tutorial, you will learn how to call API of node js express app from react js app and also how to send data in the node js app from react app and store it on MySQL database.

How to Send/Pass Form Data from React js App to Node js Express + MySQL

Let’s use the following steps to send/pass form data from react js app to node js express with mysql:

  • Create React JS Frontend App
    • Step 1 – Create React App
    • Step 2 – Install validator and Bootstrap
    • Step 3 – Create Form Validation Class
    • Step 4 – Create Registration Form in App.js
  • Create Node JS Express Backend
    • Step 5 – Create Node Js App
    • Step 6 – Create Table In Database
    • Step 7 – Install Express body parser cors and MySQL Dependencies
    • Step 8 – Create Apis in Server JS File
    • Step 9 – Start Node Js Express App

Create React JS Frontend App

Step 1 – Create React App

In this step, open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app my-react-app

To run the React app, execute the following command on your terminal:

npm start

Check out your React app on this URL: localhost:3000

Step 2 – Install Validator and Bootstrap

In this step, execute the following command to install react boostrap library into your react app:

npm install bootstrap --save

npm install --save validator

Add bootstrap.min.css file in src/App.js file:

import React, { Component } from 'react'

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

function App() {
  return (
    <div>
      <h2>How to Add Custom Validatin with Forms in React</h2>
    </div>
  );
}

export default App;

Step 3 – Create Form Validation Class

In this step, create MyForm.js file. So, visit the src directory of your react js app and create a custom validation component file named MyForm.js. And add the following code into it:

import React from 'react'

class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: '' };
  }

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

  handleSubmit = (event) => {
    alert('A form was submitted: ' + this.state);

    fetch('http://localhost:3000/store-data', {
        method: 'POST',
        // We convert the React state to JSON and send it as the POST body
        body: JSON.stringify(this.state)
      }).then(function(response) {
        console.log(response)
        return response.json();
      });

    event.preventDefault();
}

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} name="name" onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

export default MyForm;

Note that, The validate() function check all field validation.

Step 4 – Import Form in App.js

In this step, create a registration form and as well as well import  MyForm.js file in src/App.js file:

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import MyForm from './MyForm'

function App() {  
    
  return (  
    <div className="App">  
      <MyForm />  
    </div>  
  );  
}  

export default App;

Create Node JS Express Backend

Step 5 – Create Node JS App

Open your terminal and execute the following command to create node js app:

mkdir my-app
cd my-app
npm init -y

Step 6 – Create Table In Database

Execute the following query and create table into your mysql database:

CREATE TABLE users(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(200)
)ENGINE=INNODB;

Step 7 – Install Express body parser cors and MySQL Dependencies

Execute the following commands to install imperative npm packages which will help us to create REST APIs for your react file upload app:

npm install --save express cors mysql body-parser

npm install nodemon --save-dev

Step 8 – Create Apis in Server JS File

In this step, create server.js file and add the following code into it:

const express = require("express");
const bodyParser = require('body-parser');
const cors = require("cors");

const app = express();

app.use(cors());
// parse application/json
app.use(bodyParser.json());
 
//create database connection
const conn = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'my_db'
});

//connect to database
conn.connect((err) =>{
  if(err) throw err;
  console.log('Mysql Connected...');
});


//add new user
app.post('/store-data',(req, res) => {
  let data = {name: req.body.name};
  let sql = "INSERT INTO users SET ?";
  let query = conn.query(sql, data,(err, results) => {
    if(err) throw err;
    res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
  });
});

app.listen(3000, () => {
  console.log("Server running successfully on 3000");
});

Step 9 – Start Node Js Express App

Start the server with the following command and then you can test the form:

npm start

OR

nodemon server.js

Conclusion

React registration/signup form validation example; In this tutorial, you have learned how to add validation rules on registration/signup forms field in react js apps.

Recommended React JS + Node JS Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

One reply to How to Send Data from React to Node js Express + MySQL

  1. I think ReactJS is an open-source JavaScript library that is used for building user interfaces specifically for single-page applications.NodeJS is primarily used for non-blocking, event-driven servers, due to its single-threaded nature. Thanks for sharing this great ideas.

Leave a Reply

Your email address will not be published. Required fields are marked *