Home > Blockchain >  why req.body.title shows 'undefined'
why req.body.title shows 'undefined'

Time:03-17

I'm new to NODE JS and practicing with some POST forms from PUG to a NODE JS server. I have a simple form to update a photo title and description posted onto mongodb. When I submit the form from the web browser the submission input comes back to the server as 'undefined'.

These two processes in POST log 'undefined': (see below with more full code)

  console.log("title:", req.body.title)
  console.log("description", req.body.description)

I've tried to use PUT instead. Weirdly I've done this before and it's worked. So I'm not sure what the issue is...

router handling the POST request:

//users.js
const express = require('express');
const router = express.Router();
const app = express();
const multer = require('multer');
const photoController = require('../controllers/photoController');
const flash = require('express-flash');
const Photo = require('../models/photoModel');
const upload = multer({
  storage: photoController.storage,
  fileFilter: photoController.imageFilter
});

// flash messaging
router.use(flash());

router.get('/', (req, res, next)=>{
  Photo.find({})
    .then((photos)=>{
      res.render('photos', {
        photos : photos,
        flashMsg: req.flash("fileUploadError")
      });
    })
    .catch((err)=>{
      if (err) {
        res.end("ERROR!");
      }
    });
});


router.get('/:photoid', (req, res, next)=>{
  console.log("finding " req.params.photoid);
  Photo.findOne({'_id': req.params.photoid})
    .then((photo)=>{
      res.render('updatePhoto', {
        photo: photo,
        flashMsg: req.flash("photoFindError")
      });
    }).catch((err)=>{
      if (err) console.log(err);
    });
});

// I think the error is below!!
router.post('/:photoid', (req, res, next)=>{
  console.log("title:", req.body.title)
  console.log("description", req.body.description)
  Photo.findOne({'_id': req.params.photoid})
    .then((photo)=>{
      var data  = {
         title: req.body.title,
         description: req.body.description
         }
      photo.set(data);
      photo.save().then(()=>{
        res.redirect('/photos');
      });
    })
    .catch((err)=>{
      if (err) console.log(err);
  });
});

PUG form:

.row
   .col-md-6.col-md-offset-3
      if flashMsg.length > 0
        .alert.alert-danger <strong>FLASH!</strong>#{flashMsg}
      p Title: #{photo.title} 
      p Description: #{photo.description}
      p Size: #{photo.size} | Filename: #{photo.originalname} | Uploaded: #{photo.createdAt}| Modified: #{photo.updatedAt}
      img(src=photo.imageurl, width="250")
      form(method='POST' action="/photos/" photo._id enctype="multipart/form-data")
        div.form-group
          label(for='name') Photo Title :
          input#name.form-control(type='text', value=photo.title name='title')
        div.form-group
          label(for='email') Description:
          input#email.form-control(type='text', value=photo.description name='description')
        div.form-group
          label(for='image') Image:
          input#name.form-control(type='hidden', name='_id' value=photo._id)
        button.btn.btn-primary(type='submit') Update Your Photo

Thanks for your help

CodePudding user response:

You should add to your code the app.use(express.json()) middleware in order to parse automatically the req.body from your request.

const express = require('express');
const router = express.Router();
const app = express();
app.use(express.json()); // Here
const multer = require('multer');
const photoController = require('../controllers/photoController');
const flash = require('express-flash');
const Photo = require('../models/photoModel');
const upload = multer({
  storage: photoController.storage,
  fileFilter: photoController.imageFilter
});
  • Related