article

Friday, September 8, 2023

Node Express JS API CRUD (Create, Read, Update and Delete) Mysql

Node Express JS API CRUD (Create, Read, Update and Delete) Mysql

https://expressjs.com/
Express JS
Fast, unopinionated, minimalist web framework for Node.js

Install
$ npm install express --savev PS C:\nodeproject> npm install express --save
https://expressjs.com/en/starter/hello-world.html

mysql
https://github.com/mysqljs/mysql
$ npm install mysql
PS C:\nodeproject>npm install mysql

run PS C:\nodeproject> node index.js
//index.js
const express= require("express");
const bodyParser= require("body-parser");

const app= express();
const port= 3001;

const Urlpth= require("./router");

app.use(bodyParser.json());

app.use("/", Urlpth);
app.use("/api/adduser",Urlpth );
app.use("/api/edituser/:id", Urlpth);
app.use("/api/updateuser/:id",Urlpth);
app.use("/api/delete/:id",Urlpth);


app.listen(port, ()=>console.log("Server running on port 3001"));
dbconnection.js
//dbconnection.js
const sqlconnection= require("mysql");

const sqldbconnection= sqlconnection.createConnection({
  host:"localhost",
  user:"root",
  password:"",
  database:"nodejsdb",
  multipleStatements:true
});
sqldbconnection.connect((err)=>{
    if(!err)
    {
    console.log("Database Connected");
    } else{
        console.log("Database Not Connected");    
    }

});

module.exports= sqldbconnection;
router.js
//router.js
const express= require("express");
const Router= express.Router();
const dbconnected= require("./dbconnection");

Router.get("/",(req, res)=>{
    const data=[{name:"cairocoders",email:"cairocodes@gmail.com"}];
    res.send(data);
});
Router.get("/api/user",(req, res)=>{
    dbconnected.query("select * from users", (err, rows, fields)=>{
        if(!err)
        {
        res.send(rows);
        } else {
            console.log(err);
        }
    })
});
Router.post("/api/adduser", (req, res)=>{
    const name= req.body.name;
    const email= req.body.email;
    const address= req.body.address;
    var sql= `INSERT INTO users(name, email, address) 
    VALUES("${name}", "${email}","${address}")`;
    dbconnected.query(sql, (err, result)=>{
        if(!err)
        {
        res.status(200).json({success:"User Record Inseted Successfully"});
        } else{
            console.log(err);
        }
    });
});
Router.get("/api/edituser/:id", (req, res)=>{
    dbconnected.query("select * from users where id='"+ req.params.id+"' ",(err, rows)=>{
      if(!err)
      {
         res.send(rows[0]);
      } else{
        console.log(err);
      }
    });
});
Router.put("/api/updateuser/:id", (req, res)=>{
    const userdata=[req.body.name, req.body.email, req.body.address];
    var sql= "UPDATE users SET name=?, email=?, address=? where id='"+ req.params.id+"' ";
    dbconnected.query(sql, userdata,(err, result)=>{
        if(!err)
        {
        res.status(200).json({success:"User Record Updated successfully"});
        } else{
            console.log(err);
        }
    });
});

Router.delete("/api/delete/:id", (req, res)=>{
    const id = req.params.id;
	console.log(id);
    var sql = "Delete FROM users WHERE id = ?";
    dbconnected.query(sql, [id], (err, result) => {
        if(!err)
        {
			res.status(200).json({success:"User Record Deleted successfully"});
        } else{
            console.log(err);
        }
    })
});

module.exports= Router;
http://localhost:3001/api/adduser
http://localhost:3001/api/edituser/5
http://localhost:3001/api/updateuser/8
http://localhost:3001/api//delete/5

Related Post