Search code examples
node.jsexpressmiddlewaremulterbody-parser

Req.body is empty and also cannot read property path of undefined


My project was working fine till last week and now all of a sudden my post requests are not working . i tried all methods and read other questions of stack overflow but was unable to fix the issue . can some one please help me?

Issue : req.body is undefined and also whenever i try upload a file "cannot read property path of undefined" is the error.

i'm using express middle ware to parse the request body . i also have my form enctype to multipart/form-data..

Code snippet is below :

require('dotenv').config()
const express = require('express');
const app = express();
const router = express.Router();
const session = require('express-session');
const fs = require(`fs`);
const mysql = require(`mysql-await`);
const path = require('path');


 app.set('view engine', 'ejs');
 app.set('views', path.join(__dirname, 'views'));
 app.use(express.static(path.join(__dirname, 'public')));
 app.use(express.json())
 app.use(express.urlencoded({ extended: true }))

 const multer = require('multer');
 const {storage} = require('../cloudinary');
 const upload = multer({storage});

 const con = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "Sujanya@1978",
      database: "dept"
 });

 con.connect((err) => {
    if (!err) {
    console.log("Connected");
    }
    else {
    console.log(err)
    }
 })

router.get('/naaccircular',(req,res)=>{
    (async () => {
           let results = await con.awaitQuery('select* from dept.naaccircular;');
       res.render('Naac_circular',{Egs : results})
    })();

   })

  router.get('/naaccriteria',(req,res)=>{
   (async () => {
          flet results = await con.awaitQuery('select* from dept.naaccriteria;');
        res.render('Naac_criteria_files',{Fgs : results})
    })();
    })





    router.post('/naacaddcircular',upload.single('circularfile'),(req,res) => {
          console.log(req.body);
          const n = req.body.circularname;
          const d = req.body.circulardate;
          const l = req.file.path;


          con.connect(function(err){
          var records = [n,d,l];
          con.query("insert into dept.naaccircular (cirname,cirlink,cirdate) 
                  VALUES (?,?,?)", [n,l,d] , function (err, result, fields){
          if (err) throw err;
        
          })
    
    
          });
          console.log(n);
          console.log(l);
          console.log(d);
          res.redirect('/naaccircular');
      })


 module.exports = router;

    
        style="margin-top:80px; background-color: white;">
        <form action="/naacaddcircular" method="POST" class="row g-3 form-container" enctype="multipart/form-data">
        <h3 style="text-align: center;">Naac Circular</h3>
        <div class="mb-3">
            <label for="ii" class="form-label">Name</label>
            <input id="ii" name="circularname" class="form-control" type="text" placeholder="Default input"
                aria-label="default input example">
        </div>
        <div class="mb-3">
            <label for="jj" class="form-label">Date</label>
            <input id="jj" name="circulardate" class="form-control" type="date">
        </div>
        <div class="input-group mb-2">
            <input type="file" class="form-control" name="circularfile"id="inputGroupFile04" aria-describedby="inputGroupFileAddon04"
                aria-label="Upload">
            <!--<button class="btn btn-outline-secondary" type="button" id="inputGroupFileAddon04">Button</button>-->
        </div>
        <button type="submit"
            class="btn btn-primary position-relative start-50 botttom-0 translate-middle-x">Upload</button>
        </form>
    </div> ```
 

Solution

  • The problem is with cloudinary module. I have rectified it, there are no errors in the post method.

    Once upload.single() function is removed from the router.post() function I'm able to get the req.body(),