Home » NodeJS » How to make Backend ready for PUT ?

How to make Backend ready for PUT ?

How to make Backend ready for PUT
http://localhost:5000/api/productlist/1

Directory Structure

Create a structure like this

Setup an Express App

Install everything

Create a Backend Folder. Then open the folder with VS Code. (Note: If using Main Folder, then do ‘cd BACKEND’)

run this:

npm i express mysql2 dotenv nodemon

Create ENV FILE

create “.env” file (do npm i dotenv if you haven’t installed env)

type these:

MYSQL_HOST= check your connection in workbench, it will say 'localhost'

MYSQL_USER= check the same connection, it will say 'root'

MYSQL_PASSWORD= password of MySQL Workbench you written in diary/any paper

MYSQL_DATABASE= After opening workbench, See the database name there 'db' 

How to use these env, read it there. [link of that article]

Now Create An Express App with index.js

first create “index.js”

// index.js

require("dotenv").config()
const express=require('express')
const app =express()

app.get('/', (req, res)=>{
    res.send('Backend successfully runned')
})

const PORT = 8000

app.listen(PORT, () => {
    console.log(`Backend Server is running on port ${PORT}`)
});

START THE SERVER

Run using nodemon: npx nodemon index.js

or simply: node index.js

Now Open localhost:8000 in browser

# Create a MySQL Table

open mysql workbench

  • Create a new schema
  • Create a table
  • Create fields ………… (fields, datatype, nn, pk, ai) (nn-not null, ai-auto increase)
  • Right click the table and select all rows
  • Fill the data

Create MySQL DB POOL ( //pool.js )

// pool.js

const mysql = require('mysql2');

const pool = mysql.createPool({
  host: process.env.MYSQL_HOST,
  user: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: process.env.MYSQL_DATABASE,
  waitForConnections: true,
  connectionLimit: 10, // Maximum number of connections in the pool
  queueLimit: 0,       // 0 means no limit for the queue
});

console.log('MySQL Pool created successfully.'); // Check if the pool is created successfully


// Test a connection from the pool
pool.getConnection((err, connection) => {
  if (err) {
    console.error('Testing: Error connecting to MySQL Pool:', err);
    return;
  }
  console.log('Testing: Successfully connected to MySQL Pool');

  // Release the connection back to the pool
  connection.release();
});

module.exports = pool; // Export the pool

Import the Pool ( // index.js )

const pool = require('./pool.js')

Use Pool in index.js (Main File)

You probably don’t need it

In your index.js (or app.js), also import the pool from db.js if you need it in the main file. If you don’t need to use the pool in index.js, you don’t need to import it there.

How to use Pool in any Router? Just import it : )

const pool = require('./../pool.js')

Output:

Create PUT Route

create a file in

  â”œâ”€â”€ /routes

  â”‚     └── routerProduct.js

//  routerProduct.js

const express = require('express');
const router = express.Router();
const pool = require('./../pool.js'); // Import the pool

// PUT route to update a product by ID
router.put('/api/productlist/:id', (req, res) => {
  const productId = req.params.id; // Get product ID from request parameters
  const {
    displayImage, firstImage, secondImage, thirdImage, fourthImage,
    fifthImage, sixthImage, seventhImage, eighthImage, ninthImage, tenthImage,
    slug, cardTitle, category, brand, soldNumber, actualPrice,
    markedPrice, rating, freeShipping, stockStatus, title,
    description, bigDescription, specification,
  } = req.body; // Destructure updated product details from the request body

  const query = `
    UPDATE table_name SET
      displayImage = ?, firstImage = ?, secondImage = ?, thirdImage = ?, fourthImage = ?,
      fifthImage = ?, sixthImage = ?, seventhImage = ?, eighthImage = ?, ninthImage = ?, tenthImage = ?,
      slug = ?, cardTitle = ?, category = ?, brand = ?, soldNumber = ?, actualPrice = ?,
      markedPrice = ?, rating = ?, freeShipping = ?, stockStatus = ?, title = ?,
      description = ?, bigDescription = ?, specification = ?
    WHERE id = ?
  `;

  const values = [
    displayImage, firstImage, secondImage, thirdImage, fourthImage,
    fifthImage, sixthImage, seventhImage, eighthImage, ninthImage, tenthImage,
    slug, cardTitle, category, brand, soldNumber, actualPrice,
    markedPrice, rating, freeShipping, stockStatus, title,
    description, bigDescription, specification, productId,
  ];

  pool.query(query, values, (err, results) => {
    if (err) {
      console.error('Error occurred while updating product:', err); // Log error
      return res.status(500).json({ message: 'Failed to update product', error: err });
    }

    if (results.affectedRows === 0) {
      // No product found with the given ID
      return res.status(404).json({ message: 'Product not found' });
    }

    console.log('Product updated successfully:', results); // Log success message
    res.status(200).json({ message: 'Product updated successfully' });
  });
});

module.exports = router;

Send in postman like this:

{
“displayImage”: “new-image-url”,
“cardTitle”: “Updated Product Title”,
“category”: “Updated Category”,
“brand”: “Updated Brand”,
“actualPrice”: 199.99,
“markedPrice”: 249.99,
“description”: “Updated description of the product.”
}