Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

react
mysql
communitycreator

How to implement a server for ReactJS and MySQL application

Nasreen

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

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.

We need to follow the following steps, in order, to achieve our goal:

  1. Create the database to store our records
  2. Create the server connection to the DB
  3. Define the endpoints for the CRUD app
  4. Create react app and define the frontend
  5. Integrate the front end and backend

The steps above are 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.

DB set-up

So, I have got the XAMMP server installed on the 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 add a blog post I will name the db–>> blog_posts). I will add the following six columns in the ‘posts’ table in my DB:

Backend implementation

Next, we will create two folders in our main app folder, one is a server(having the backend structure) and one is the client (containing the front end files). So, if you’ve named your parent folder “blog”, then the folder structure should look like this:

Now we’ll create a config folder inside server folder and a db.js file inside it so that we can 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;

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}`)
})

The Github repo for the backend part is: Github

All the backend has been taken care of, so now, we will create a react app where all the frontend fun takes place. The link for the frontend part of the article, is: link

I hope you’ll find this article helpful.

Happy coding guys and have a great day!

RELATED TAGS

react
mysql
communitycreator
RELATED COURSES

View all Courses

Keep Exploring