In this tutorial, you will learn how to send or pass form data from the react js app to the node js express app and store it on MySQL database using fetch().
In this example tutorial, we will create a simple signup or registration form, and post the data from this React JS form to a Node JS application using the fetch() method, and store it in a MySQL database.
How to Post Form Data from React js to Node js Express + MySQL
Let’s use the following steps to send form data from react js app to node js express and store it in MySQL database:
Step 1 – Create a 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 and Set up Validator, Bootstrap
In this step, execute the following commands to install validator and bootstrap 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
Create a MyForm.js
file in src directory of your react js app, and create a form with custom validation rules and messages in 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
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;
Step 5 – Create Node JS App
Open your terminal and execute the following command to create a new node js application:
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
In this tutorial, you have learned how to send data from react to node js and store it in MySQL db.
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.