Middleware in router showing req.body empty, however in actual data does exist in post request

Issue

I am trying to access req.body in express middleware in a router, however it is consoling empty req.body. However in actual data does exist. I am already using body-parser at app level but it is not working for me. Below is my code, I am trying to access req.body in authorization middleware in categories.js file

index.js

const express = require('express');
const bodyParser = require('body-parser');

//Importing Routers
const customersRouter = require('./routes/customers');
const categoriesRouter = require('./routes/categories');
const itemsRouter = require('./routes/items');
const usersRouter = require('./routes/users');
const tablesRouter = require('./routes/tables');
const ridersRouter = require('./routes/riders');
const taxtypesRouter = require('./routes/taxtypes');
const branchesRouter = require('./routes/branches');
const subscribeRouter = require('./routes/subscription');
const loginRouter = require('./routes/login');

//Importing Database Connection
//const db = require('./dbConnection');


const app = express();
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server is listening at port ${PORT}`));

app.use('/subscribe', subscribeRouter);
app.use('/login', loginRouter);
app.use('/client/:clientID/user/:userID/customers', customersRouter);
app.use('/:clientID/categories', categoriesRouter);
app.use('/client/:clientID/user/:userID/items', itemsRouter);
app.use('/client/:clientID/user/:userID/users', usersRouter);
app.use('/client/:clientID/user/:userID/tables', tablesRouter);
app.use('/client/:clientID/user/:userID/riders', ridersRouter);
app.use('/client/:clientID/user/:userID/taxtypes', taxtypesRouter);
app.use('/client/:clientID/user/:userID/branches', branchesRouter);

router file categories.js

const express = require('express');
const util = require('util');
const categoriesRouter = express.Router();
const verifyToken = require("../functions/userVarification");
const multer = require('multer');
const fs = require('fs');
var path = require('path');

//Importing Database Connection
const db = require('../dbConnection');
const query = util.promisify(db.query).bind(db);


// File Uploading through Multer
var storage = multer.diskStorage({
    destination: (req, file, cb) => {
        const path = `./uploads/${req.body.clientID}/categories`;
        fs.mkdirSync(path, { recursive: true });
        return cb(null, path);
    },
    filename: function (req, file, cb) {
        cb(null, req.body.clientID + "_" + "Category_" + file.originalname.replace(".", "_") +"_" + Date.now() + path.extname(file.originalname)) //Appending extension
    }
})

var upload = multer({ storage: storage });

function authorization(req, res, next) {
    //Only Admins are allowed to add category
    const roleID = parseInt(req.authData.roleID);
    if (roleID !== 1) res.status(403).json({ msg: "Sorry your are not authorized to add categories" });
    else {
        next();
    }
}

categoriesRouter.post('/', verifyToken, (req, res, next) => authorization(req, res, next), upload.single('Image'), (req, res) => {

    //destructuring request body
    const clientID = parseInt(req.body.clientID);
    const userID = parseInt(req.body.userID);
    const name = req.body.Name;
    const branches = req.body.Branches;
    const color = req.body.Color;
    let imageSource = `uploads/${req.body.clientID}/categories/${req.file.filename}`;
    const imageInPOS = req.body.ImageInPOS;
    const visibilityInPOS = req.body.VisibilityInPOS;

        try {
            (async () => {
                //Create Local Category ID
                const SQL1 = `SELECT COUNT(ClientID) AS 'Categories' FROM categories WHERE ClientID = ${clientID};`;
                let counter = await query(SQL1);
                counter = counter[0].Categories + 1;
                const localCategoryID = 'CT' + ('00' + counter).slice(-3);
                //SQL for Adding Category in the database
                const SQL2 = `INSERT INTO categories (CategoryID, LocalCategoryID, ClientID, CategoryName, ShowInBranches, CategoryColor, ImageSrc, DisplayInPOS, DisplayImage) 
                VALUES (NULL, '${localCategoryID}', ${clientID}, '${name}', '${branches}', '${color}', '${imageSource}', ${visibilityInPOS}, ${imageInPOS})`;
                const addedCategory = await query(SQL2);
                if(addedCategory.affectedRows > 0) {
                    res.status(200).json({ msg : "Category have been added"});
                }
                else {
                    res.status(500).json({ msg: "Something went wrong" });   
                }
                
            })()

        }
        catch (err) {
            res.status(500).json({ msg: "Something went wrong" });
            return;
        }
});

module.exports = categoriesRouter;

Solution

the body-parser module don’t require to explicitly install.

Its provided under the methods express.json() and express.urlencoded().

so add

 app.use(express.urlencoded({extended: true})); 
 app.use(express.json())

and remove

require('body-parser');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

Answered By – ht006

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published