04-Apr-2023
.
Admin
Hello Friends,
In this tutorial, I will show you how to send data from reacting to node js express. In this article, we will implement a send/pass data from react js to node.js express & MySQL. if you have a question about how to send form data from react to express with code examples then I will give a simple example with solution. you can understand the concept of building a rest API with node.js express and MySQL
This tutorial will create a simple form in react js app and send the data of this form to the 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 the API of the 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.
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 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
In this step, create a 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 good 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 a 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 a server.js file and add the following code to 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
I hope it can help you...
#Node.js Express
#Node JS