Basic CRUD App setup with React, Node.js, Express, MySQL
This is a quick tutorial to set up your CRUD application using React as a frontend and Node.js-Express server as a backend with MySQL as database service.
- MySQL — is the most popular Open Source Relational SQL Database Management System.
- Node.js — is an asynchronous event-driven JavaScript runtime, is designed to build scalable network applications.
- Express.js — is a minimal and flexible Node.js web application framework.
- React.js — is a declarative, efficient, and flexible JavaScript library for building user interfaces.
Creating a simple Node.js — Express server
So, let’s begin the application development by creating a directory for this project. Once you are done, open up the terminal and change the directory to the project directory. Now you need to set up the project configuration, type the following command on the terminal.
npm init -y
It will create a package.json file in this folder.
Now, you need to install the required packages.
npm i express body-parser mysql2
npm i -D nodemon
Your package.json file will look something like this.
{
"name": "React-Node-Express-MySQL",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mysql2": "^2.1.0"
},
"devDependencies": {
"nodemon": "^2.0.4"
}
}
create a server.js file.
add this two-line to package.json”scripts”: {
…
“start”: “node server.js”,
“start:dev”: “nodemon server.js”
},
...
"scripts": {
...
"start": "node server.js",
"start:dev": "nodemon server.js"
},
...
run this command on the terminal
npm run start:dev
It will show this output
[nodemon] starting `node server.js`
Server started at port 5000
Connecting to MySQL database
create a db.js file
Now our server is running on http://localhost:5000 and MySQL database is connected. Now we need to create routes so that we can send requests to the server from our frontend.
open a browser and go to http://localhost:5000/products link, you’ll see the products store in the database.
Note that to view the products you need to add product table and some of the products to the database.
Creating frontend with React
First of all, create a frontend folder and open a terminal on that folder and run -
npx create-react-app appName
cd appName
npm start
so, our frontend is running on port 3000 and our backend is on port 5000.
add the following line to frontend’s package.json -
...,
"proxy": "http://localhost:5000",
...
open app.js file in src folder and add this code
open up your browser and open http://localhost:3000. Your products will show on the web page.
This brings to the end of this article. This is a quick tutorial to startup your React-Node application with MySQL.
Start building your awesome website…
happy hacking…..