DEV Community 👩‍💻👨‍💻

yash kumat
yash kumat

Posted on

React Node MySql

In this lesson we will learn how add, read, delete data from MySql database (phpmyadmin, MySql Workbench, etc) using React in Frontend and Node Js Server.

We will also learn how to use Axios, Express, CORS, mysql package, prepared statements and many more things in this project.

  • Client

We are using Axios to send request to our server running on port 9000.

  1. Create'http://localhost:9000/create_user', 
    username : username,
    password: encodedPassword
    console.log("request Send!")
Enter fullscreen mode Exit fullscreen mode, data_object).then((err, success)=>{})

  1. Read
Enter fullscreen mode Exit fullscreen mode


  1. Delete
   console.log("User Deleted")
Enter fullscreen mode Exit fullscreen mode

Axios.delete(endpoint+param).then((err, success)=>{})

  • Server

// Import Express
const express =  require('express')

Cross-origin resource sharing - 
Cross-origin resource sharing is a mechanism that allows
restricted resources on a web page to be requested from
another domain outside the domain from which the first
resource was served.
const cors = require('cors')

// Create express application
const app = express()

// Use CORS

// Recognise the incoming Request Object as a JSON Object

// Import MySql
const mysql = require('mysql')

// Connect to MySql database
const db = mysql.createConnection({
    user: "root",
    host: "localhost",
    password: "",
    database: "react-mysql"

// Fire app at port 9000
app.listen(9000, ()=>{
    console.log("Server Started. Jai Shree Ram!")
    db.connect(function(err) {
        if (err) throw err;

// Insert into database'/create_user', (req,res)=>{
    const username = req.body.username
    const password = req.body.password

    db.query("INSERT INTO users (username, password) VALUES (?, ?)", [username, password], (err, result)=>{
            console.log("value inserted!");

// Get from database
    db.query("SELECT * FROM users", (err,result)=>{

// Delete from database
    const id =

    db.query("DELETE FROM users WHERE id = ?", id, (err,result)=>{
Enter fullscreen mode Exit fullscreen mode

1 . Insert

db.query("INSERT INTO table_name (col1, col2, col3, ...) VALUES (?, ?, ?, ...)", [val1, val2, val3, ...], (err, result)=>{})

Note - values are not directly passed but send separately in array for SQL injections prevention.

2 . Get

db.query("SELECT * FROM table_name", (err,result)=>{})

3 . Delete

db.query("DELETE FROM table_name WHERE id = ?", id, (err,result)=>{})

Note - when we have to pass one value we can send it directly instead of array into prepared statement.

GitHub Link -

Top comments (0)

Find and follow new tags! 🤔 Did you know?   DEV has a variety of tags to help you find the content you like. Find and follow your favorite tags