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 {
    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
      slug = ?, cardTitle = ?, category = ?, brand = ?, soldNumber = ?, actualPrice = ?,
      markedPrice = ?, rating = ?, freeShipping = ?, stockStatus = ?, title = ?,
      description = ?, bigDescription = ?, specification = ?
    WHERE id = ?
  `;

  const values = [
    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;

Create A PUT Route (+ MULTER)

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

// PUT route to handle image upload and update data in MySQL
router.put('/upload/:id', upload.array('images', 11), (req, res) => {
  const files = req.files;
  const { id } = req.params; // Get the ID of the item to update

  // Prepare an object to hold image paths for each specified column
  const imageData = {
    displayImage: files[0] ? files[0].path : null,
    firstImage: files[1] ? files[1].path : null,
    secondImage: files[2] ? files[2].path : null,
    thirdImage: files[3] ? files[3].path : null,
    fourthImage: files[4] ? files[4].path : null,
    fifthImage: files[5] ? files[5].path : null,
    sixthImage: files[6] ? files[6].path : null,
    seventhImage: files[7] ? files[7].path : null,
    eighthImage: files[8] ? files[8].path : null,
    ninthImage: files[9] ? files[9].path : null,
    tenthImage: files[10] ? files[10].path : null,
  };

  // Extract additional input fields from the request body
  const {
    slug,
    cardTitle,
    category,
    brand,
    soldNumber,
    actualPrice,
    markedPrice,
    rating,
    freeShipping,
    stockStatus,
    title,
    description,
    bigDescription,
    specification
  } = req.body;

  // SQL query to update image paths and other input fields in the database
  const query = `
    UPDATE my_db 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 = ?
  `;

  // Execute the query with the values from imageData and input fields
  pool.query(query, [
    imageData.displayImage, imageData.firstImage, imageData.secondImage,
    imageData.thirdImage, imageData.fourthImage, imageData.fifthImage,
    imageData.sixthImage, imageData.seventhImage, imageData.eighthImage,
    imageData.ninthImage, imageData.tenthImage,
    slug, cardTitle, category, brand, soldNumber,
    actualPrice, markedPrice, rating, freeShipping, stockStatus,
    title, description, bigDescription, specification,
    id // Use the ID to identify which record to update
  ], (err, result) => {
    if (err) {
      console.error('Error updating data in the database:', err);
      return res.status(500).json({ message: 'Error updating data in the database' });
    }

    if (result.affectedRows === 0) {
      return res.status(404).json({ message: 'Record not found' });
    }

    // Send success response
    res.json({ message: 'Images and data updated successfully!', imageData });
  });
});

module.exports = router;

Testing it through PostMan

1. Configure the Route:

  • Method: PUT
  • URL: http://<your-server-url>/api/upload/1

Replace 1 with the ID of the item you want to update.

3. Add Other Input Fields:

  • In the same Bodyform-data, add additional input fields with Text as their type.
KeyValue
slugunique-slug-123
cardTitleSample Product
categoryElectronics
brandBrandName
soldNumber10
actualPrice500.00
markedPrice600.00
rating4.5
freeShippingtrue
stockStatusIn Stock
titleProduct Title
descriptionShort product description
bigDescriptionDetailed product description
specificationTechnical specifications

2. Add Files (Images):

  • Go to Bodyform-data.
Key           | Type | Value
--------------|------|------------------------
images        | File | firstImage.png
images        | File | secondImage.png
images        | File | thirdImage.png

Repeat this for all the images you want to upload. You can upload up to 11 images.

NOTE: if you don’t put “images” in all key, there will come error ( Multer error: Unexpected field )

4. Headers:

  • Postman automatically ensures its Content-Type is set to multipart/form-data —postman does this when you add files in th form-data section. SO NO NEED TO WORRY!

5. Send the Request:

  • Click Send

Expected JSON Response:

{
    "message": "YOUR PUT REQUEST WAS SUCCESSFUL! Data updated successfully",
    "updatedData": {
        "message": "Images and data updated successfully!",
        "imageData": {
            "displayImage": "Add a heading-2024-10-28-21-19-20.png",
            "firstImage": "Screenshot 2024-10-25 045548-2024-10-28-21-19-20.png",
            "secondImage": null,
            "thirdImage": null,
            "fourthImage": null,
            "fifthImage": null,
            "sixthImage": null,
            "seventhImage": null,
            "eighthImage": null,
            "ninthImage": null,
            "tenthImage": null
        },
        "updatedFields": {
            "slug": "unique-slug-123",
            "cardTitle": "Sample Product",
            "category": "Hailoo",
            "brand": "BrandName",
            "soldNumber": "10",
            "actualPrice": "500",
            "markedPrice": "600",
            "rating": "4.5"
        }
    }
}