DEV Community

loading...

Simple React JS and MySQL Integration -- CRUD App (Backend)

nasreenkhalid profile image NasreenKhalid ・3 min read

Hey guys, today I am demonstrating a very simple React app integrated with MySql db through a simple CRUD app. I know the app seems very trivial but believe me there is a lot to learn and can be beneficial to you some day.

Please note that in this article we will take care of the backend part and in the end I will link another article that corresponds to the front end of the application.

So, to list down the steps we need to follow in order to achieve our goal are:
Create the database to store our records
Create the server connection to the db
Define the endpoints for CRUD app
Create react app and define the frontend
Integrate the front end and backend

Above is a high level description of what we are trying to achieve, we may jump from one step to another but eventually we will reach the goal.

So, I have got XAMMP server installed on system for MySQL db to host upon. I will go to my browser and write localhost/phpmyadmin to open up the database console and create a new database (since I am creating a blog posts webpage where you can create, list, delete and like a blog post so I will name the db-->> blog_posts). I will add the following six columns in the 'posts' table in my db:
Alt Text

Next, we will create two folders in our main app folder, one is server(having the backend structure) and one is client (containing the front end files). So if you've named your parent folder blog then the folder structure should look like this:
Alt Text
Now we'll create a config folder in server folder and a db.js file inside to define our db configurations:
server ->> config ->> db.js:

const mysql = require('mysql')
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:"blog_posts" 
})

module.exports = db;
Enter fullscreen mode Exit fullscreen mode

Now in the server folder we will create an index.js file where we will define all our backend logic i-e the endpoints/routes to get, update and delete queries:

const express = require('express');
const db = require('./config/db')
const cors = require('cors')

const app = express();
const  PORT = 3002;
app.use(cors());
app.use(express.json())

// Route to get all posts
app.get("/api/get", (req,res)=>{
db.query("SELECT * FROM posts", (err,result)=>{
    if(err) {
    console.log(err)
    } 
res.send(result)
});   });

// Route to get one post
app.get("/api/getFromId/:id", (req,res)=>{

const id = req.params.id;
 db.query("SELECT * FROM posts WHERE id = ?", id, 
 (err,result)=>{
    if(err) {
    console.log(err)
    } 
    res.send(result)
    });   });

// Route for creating the post
app.post('/api/create', (req,res)=> {

const username = req.body.userName;
const title = req.body.title;
const text = req.body.text;

db.query("INSERT INTO posts (title, post_text, user_name) VALUES (?,?,?)",[title,text,username], (err,result)=>{
   if(err) {
   console.log(err)
   } 
   console.log(result)
});   })

// Route to like a post
app.post('/api/like/:id',(req,res)=>{

const id = req.params.id;
db.query("UPDATE posts SET likes = likes + 1 WHERE id = ?",id, (err,result)=>{
    if(err) {
   console.log(err)   } 
   console.log(result)
    });    
});

// Route to delete a post

app.delete('/api/delete/:id',(req,res)=>{
const id = req.params.id;

db.query("DELETE FROM posts WHERE id= ?", id, (err,result)=>{
if(err) {
console.log(err)
        } }) })

app.listen(PORT, ()=>{
    console.log(`Server is running on ${PORT}`)
})
Enter fullscreen mode Exit fullscreen mode

Github repo for the backend part is:https://github.com/NasreenKhalid/Blog-React-CRUD-MYSQL/tree/master/server

Uptil now, all the backend has been taken care of and now we will create a react app where all the frontend fun takes place, the link for the frontend part of the article is:
https://dev.to/nasreenkhalid/simple-react-js-and-mysql-integration-crud-app-frontend-3i0l

I hope you'll find this article helpful.

Happy coding guys and have a great day!

Discussion (0)

pic
Editor guide