0

I am new to Node js and trying to create a blog system. When i tried to console the posted value in categories.js file, i am getting value as "undefined". I am using post.js for adding new posts and category.js for adding new categories.

Here is my app.js file.

var createError = require('http-errors');
var express = require('express');
var expressValidator = require('express-validator');
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var multer = require('multer');
var upload = multer({dest: './public/images/uploads'});
var flash = require('connect-flash');
var logger = require('morgan');
var mongodb = require('mongodb');
var db = require('monk')('localhost/nodeblog');

var indexRouter = require('./routes/index');
var posts = require('./routes/posts');
var categ = require('./routes/categories');

var app = express();

app.locals.moment = require('moment');

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// Session
app.use(session({
  secret: 'secret',
  resave: true,
  saveUninitialized: true
}));

// Validator
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
    var namespace = param.split('.')
    , root = namespace.shift()
    , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }

    return {
      param: formParam,
      msg: msg,
      value: value
    };
  }
}));

// Connect Flash
app.use(require('connect-flash')());
app.use(flash());
app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

// Make our db accessible to our router
app.use(function(req, res, next) {
  req.db = db;
  next();
});

app.use('/', indexRouter);
app.use('/posts', posts);
app.use('/categories', categ);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Here is my post.js file

var express = require('express');
var router = express.Router();
var mongodb = require('mongodb');
var multer = require('multer');
var upload = multer({dest: './public/images/uploads'});
var db = require('monk')('localhost/nodeblog');

router.get('/add', function(req, res, next) {
    var categories = db.get('categories');
    categories.find({}, {}, function(err, categories) {
        res.render('addpost', {
            "title" : "Add Post",
            "categories": categories
        });
    });
});

router.post('/add', upload.single('profileimage'), function(req, res, next) {

    // Getting Form Values 

    var title       = req.body.title;
    console.log(title);
    var category    = req.body.category;
    var body        = req.body.body;
    var author      = req.body.author;
    var date        = new Date();

    if(req.file) {
        var profileimage = req.file.filename;
    } else {
        var profileimage = 'noimage.png';
    }

    // Form Validation
    req.checkBody('title', 'Title Field is required').notEmpty();
    req.checkBody('body', 'Body field is required').notEmpty();

    // Check for Errors
    var errors = req.validationErrors();

    if(errors) {

        res.render('addpost', {
            "errors": errors,
            "title": title,
            "body": body
        });
    } else {
        var posts = db.get('posts');

        // Submitting values to DB
        posts.insert({
            "title": title,
            "body": body,
            "category": category,
            "date": date,
            "author": author,
            "profileimage": profileimage
        }, function(err, post) {
            if(err) {
                res.send("There is an issue in submitting the post");
            } else {
                req.flash('success','Post Submitted Successfully');
                res.location('/');
                res.redirect('/');
            }
        });
    }
});



module.exports = router;

Here is my category file.

var express = require('express');
var router = express.Router();

router.get('/add', function(req, res, next) {
    res.render('addcategory', {
        "title" : "Add Category"
    });
});

router.post('/add', function(req, res, next) {

    // Getting Form Values 
    var title       = req.body.title;
    //console.log(req.body);
    console.log(title);
});



module.exports = router;

Here is the addcategory jade file.

extends layout

block content
    h1=title
    ul.errors
        if errors
            each error, i in errors
                li.alert.alert-danger #{error.msg}
    form(method='post', action='/categories/add', enctype='multipart/form-data')
        .form-group
            label Title:
            input.form-control(name='title',type='text')
        input.btn.btn-default(name='submit',type='submit',value='Save')

Here is post jade file.

extends layout

block content
    h1=title
    ul.errors
        if errors
            each error, i in errors
                li.alert.alert-danger #{error.msg}
    form(method='post', action='/posts/add', enctype='multipart/form-data')
        .form-group
            label Title:
            input.form-control(name='title', type='text')
        .form-group
            label Category
            select.form-control(name='category')
                each category, i in categories
                    option(value= '#{category.title}') #{category.title}
        .form-group
            label Body
            textarea.form-control(name='body', id='body')        
        .form-group
            label Main Image
            input.form-control(name='profileimage', type='file')
        .form-group
            label Author
            select.form-control(name='author')
                option(value='Deepesh') Deepesh
                option(value='Sudha') Sudha
        input.btn.btn-default(name='submit', type='submit', value='Save')
        script(src='/ckeditor/ckeditor.js')
        script
            | CKEDITOR.replace('body');

I am getting req.body value in post.js. But when i tried to get the same in categories.js, i am getting the value as undefined. I need to get the value of title in categories file, where the same should work in post file.

Can you guys find me a solution for the same. I tried from my end, but didn't get a proper solution.

Vishnu
  • 704
  • 12
  • 34
  • 1
    Multer is nice and does the body parsing for you in the first case. In the second there is no multer and no body-parsing, thus no body and no body variables. – ippi Jun 18 '18 at 16:49
  • @ippi : So do i need to include multer in category file? – Vishnu Jun 18 '18 at 17:05
  • Im not sure how much overkill it is to use mutler as body parser. maybe it works fine. i would probably go search npm for the most popular one though... – ippi Jun 18 '18 at 17:12
  • @ippi: I tried including multer in category file, but still same situation – Vishnu Jun 18 '18 at 17:14
  • maybe multer only triggers if you upload a file? Im still fairly certain its multer that is fixing your body – ippi Jun 18 '18 at 17:17

1 Answers1

0

Routing refers to determining how an application responds to a client request to a particular endpoint. you created 2 routers for the same endpoint.

router.post('/add', function(req, res, next) {} //in categories.js and post js

once you requested data, data will go to specified address and router will take it and handle it. so you are getting the request to post.js and express handles it and then responds it. so that request will be ended.

but in categories.js you are waiting for the same request which is already gone. if you wanna test it, comment out the router.post in the post.js and and you will see that express will handle the request in categories.js.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202