Monday, January 20, 2020

node.js: req.body.PARAM_NAME fails returning undefined


Many times a failure comes from subtle things.

Both app.post/app.get  and  router.post/router.get accepts req.body.PARAM_NAME.

Example:

app.get('/', function(req,res){
 var email = req.body.email;
 var password = req.body.passwd;
 console.log('email: ' + email);
 console.log('pass: ' + password);
 res.render("index");
});

router.get('/alo/', function(req, res, next) {
 var email = req.body.email;
 var password = req.body.passwd;
 console.log('email: ' + email);
 console.log('pass: ' + password);
 res.render('alo', { title: 'Alo Express!' });
});

When using router and req.body returns undefined values, check if the code is well implemented, if not missing module.exports clause.

Follow by the example.

app.js file:
..
const indexRouter = require('./routes/indexRouter');
app.use('/', indexRouter);
..
module.exports = app;
 
indexRouter.js file:
..
const router = express.Router();
..
router.get('/alo/', function(req, res, next) {
  res.render('alo', { title: 'Alo Express!' });
});
..
module.exports = router;
Naturally the dependencies and app's configuration must be implemented, for example:
const express = require('express');
const bodyParser = require('body-parser');
const cookeParser = require('cookie-parser');
const app = express();
const passport = require('passport');
const { check, validationResult } = require('express-validator');
const session = require('express-session')
const hbs = require('express-hbs');
const flash = require('flash');
const router = express.Router();
const view_path = __dirname + '/views/';
const public_path = __dirname + '/public/';
app.use(express.static(view_path))
app.use(express.static(public_path));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookeParser());
app.use(passport.initialize());
app.use(passport.session());
app.set('view engine', 'html');
app.engine('html', require('hbs').__express);
 
@SEE:
Usando middlewares

 

No comments:

Post a Comment

eclipse: java: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder" or Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

  >PROBLEM Using Eclipse, you try to run a simple logging test using "org.slf4j.Logger" like the sample below: package Test; im...