In express 4.x req.body is undefined - node.js

I just moved to express.js 4.8.7 from 3.x.
I am getting error in express 4.x, "req.body" is undefined.
When I google it. I found that, I have to install "body-parser' module. Even after installing "body-parser' module, I am getting "req.body" undefined.
I am not sure what I need to do. Below is my app.js code
var express = require('express')
, path = require('path')
, redis = require("redis")
, mongoose = require('mongoose')
, favicon = require('serve-favicon')
, compression = require('compression')
, bodyParser = require('body-parser')
, methodOverride = require('method-override')
, errorHandler = require('errorhandler')
, cookieParser = require('cookie-parser')
, morgan = require('morgan')
, multer = require('multer')
, session = require('express-session');
var app = express();
var router = express.Router();
router.use(function(req, res, next) {
console.log('%s %s %s', req.method, req.url, req.path);
next();
});
var routes = require('./routes')(app);
mongoose.connect('mongodb://localhost/abc');
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/img/favicon.ico'));
app.use(morgan('dev'));
app.use(methodOverride());
app.use(session({resave: true, saveUninitialized: true, secret: 'uwotm8'}));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
app.use(multer({ dest: './uploads/'}));
app.use(methodOverride('X-HTTP-Method'));
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(methodOverride('X-Method-Override'));
app.use(compression({'threshold': 512}));
app.use(express.static(path.join(__dirname, 'public')));
if ('development' == app.get('env')) {
app.use(errorHandler());
}
app.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Error happends in my router callback function.
app.route('/xhr/abc').post(function (req, res) {
if (req.xhr) {
var language = req.headers["accept-language"];
...
var reqBody = req.body;
...
}

You need to make sure that your routes come after your included middleware, since middleware/routes/etc. are executed in order in Express 4.

Related

Nodejs CANNOT GET

I've been trying to do a route in Express. For example one /about route, but it doesn't work.
var express = require('express');
var app = express();
var router = express.Router();
var moment = require('moment');
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.get('/', function (req, res) {
//some action
});
app.get('/time', function (req, res) {
//...
});
app.get('/about', function (req, res) {
res.send('about');
});
Currently after calling url/about I'm getting Cannot GET /about as a return and after some research I've got no idea how to resolve this issue. They even describe it that way in the official express docs.
Thank you in advance.
You have something like this in your code? :
app.listen(SERVER_PORT, function () {
console.log("Server successfully started on port:" + SERVER_PORT); });
We should have something like this:
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
const app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/about', routes.about);
and also in the views folder: about.jade

Express creating lots of sessions

I have only realised that this has been happening.
My stack:
NodeJS
Express
PassportJS
Angular
MongoDB with Mongoose
When I log into my website, I see that the collection sessions is created, with one record (as one would expect). Then, I navigate around the website and noticed that my sessions have goes to 13 records. Then, I navigate some more and I see that it has gone over 27.
What in the world is going on? Am I doing something that is causing this?
My main app.js file is below:
var config = require('./config/config.js');
var express = require('express');
var favicon = require('serve-favicon')
var app = express();
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var ConnectMongo = require('connect-mongo')(session);
var mongoose = require('mongoose').connect(config.dbURL);
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var bodyParser = require('body-parser');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('hogan-express'));
app.set('view engine', 'html');
app.use(favicon(path.join(__dirname, 'public', '/images/favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(session({
secret:config.sessionSecret,
store: new ConnectMongo({
mongooseConnection:mongoose.connections[0],
stringigy:true,
touchAfter: 24 * 3600
}),
saveUninitialized:true,
resave:true
}));
app.use(session({secret:config.sessionSecret, saveUninitialized:true, resave:true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
require('./schemas/allSchemas.js')(mongoose);
require('./auth/passportAuth.js')(passport, FacebookStrategy, config, mongoose, moment);
//Main URL router
require('./routes/routes.js')(express, app, passport, mongoose);
app.listen(3000, function(){
console.log('App is working on Port 3000');
});
Each one of my sessions look like the below (if it helps in any way):
{
"_id": "cSqLjOGJlYBvNLYJ8v6zXqtqzuIcGwbx",
"session": "{\"cookie\":{\"originalMaxAge\":null,\"expires\":null,\"httpOnly\":true,\"path\":\"/\"}}",
"expires": "2017-10-10 22:46:09",
"lastModified": "2017-09-26 22:46:09"
}
Try this
var config = require('./config/config.js');
var express = require('express');
var favicon = require('serve-favicon')
var app = express();
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var ConnectMongo = require('connect-mongo')(session);
var mongoose = require('mongoose').connect(config.dbURL);
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var bodyParser = require('body-parser');
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('hogan-express'));
app.set('view engine', 'html');
app.use(favicon(path.join(__dirname, 'public', '/images/favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session({
secret:config.sessionSecret,
store: new ConnectMongo({
mongooseConnection:mongoose.connections[0],
stringigy:true,
touchAfter: 24 * 3600
}),
saveUninitialized:true,
resave:true
}));
app.use(passport.initialize());
app.use(passport.session());
require('./schemas/allSchemas.js')(mongoose);
require('./auth/passportAuth.js')(passport, FacebookStrategy, config, mongoose, moment);
//Main URL router
require('./routes/routes.js')(express, app, passport, mongoose);
app.listen(3000, function(){
console.log('App is working on Port 3000');
});

node express public folder 404 error

I got a very similar problem with this post Learning Node - Express Public folder not working
I added to my server.js
app.use("public",express.static(__dirname + '/public'));
But when I do
http://localhost:8081/public/css/styles.css
http://localhost:8081/styles.css
Neither works. I got "Cannot GET /public/css/styles.css" and "Cannot GET /styles.css" respectively.
Here is my server.js
var express = require('express')
, cors = require('cors')
, app = express()
, mongoose = require('mongoose')
, models = require('./models')
, bodyParser = require('body-parser')
, controllers = require('./controllers')
, port = 8081//process.env.PORT || 3000
// Config
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.set('views', __dirname + '/views')
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use("public",express.static(__dirname + '/public'));
app.use('/', controllers);
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost/db', function (err) {
if (err) throw err;
console.log("mongoose connected")
var server = app.listen(port, function () {
var host = server.address().address
var port = server.address().port
console.log("RESTful Web Services listening at http://%s:%s", host, port)
})
})
Here is the index.js in the controller folder
var express = require('express')
, router = express.Router()
, users = require('./api/users.js')
router.use('/api/user', users);
router.get('/', function (req, res) {
res.render('index.html')
})
//router.use(express.static('public'));
//router.use(express.static('views'));
router.get('/views/demo', function (req, res) {
res.sendFile('/views/demo.html')
})
module.exports = router
Actually, if I run
http://localhost:8081/views/demo.hmtl
I would again get "Failed to load resource: the server responded with a status of 404 (Not Found)"
What did I miss?
I added the following to the server.js and it worked.
app.use('/views', express.static(path.resolve(__dirname, 'views')));
app.use('/public', express.static(path.resolve(__dirname, 'public')));

`Nodejs - Express` - getting error as `ReferenceError: bodyparser is not defined`

I am calling the config file from server.js. when i call the config file, I am getting the error as ReferenceError: bodyparser is not defined. I don't understand the wrong with my end.
any one help me to sort this?
here is my config file :
var
path = require('path'),
routes = require('./routes'),
exphbs = require('express-handlebars'),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
morgan = require('morgan'),
methodOverride = require('method-override'),
errorHandler = require('errorhandler');
module.exports = function(app) {
app.use(morgan('dev'));
app.use(bodyParser({
uploadDir:path.join(__dirname, 'public/upload/temp')
}));
app.use(methodOverride());
app.use(cookieParser('some-secret-value-here'));
routes(app);
app.use('/public/', express.static(path.join(__dirname, '../public')));
if ('development' === app.get('env')) {
app.use(errorHandler());
}
return app;
};
server.js:
var express = require('express'),
config = require('./server/configure'),
app = express();
app
.set( "port", process.env.PORT || 3300 );
app
.set( "views", __dirname + '/views');
app = config( app );
// app
// .get('/', function( req, res ) {
// res.send( 'Hello World' );
// } );
app
.listen( app.get('port'), function () {
console.log('Server up: http://localhost:' + app.get('port'));
})
update
module.exports = function(app) {
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser({
uploadDir:path.join(__dirname, 'public/upload/temp')
}));
app.use(methodOverride());
app.use(cookieParser('some-secret-value-here'));
routes(app);
app.use('/public/', express.static(path.join(__dirname, '../public')));
if ('development' === app.get('env')) {
app.use(errorHandler());
}
return app;
};
Add following inside function in config.js
// parse application/json
app.use(bodyParser.json());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse the raw data
app.use(bodyParser.raw());
// parse text
app.use(bodyParser.text());
Reference to bodyParser documentation
Updated code:
In configure.js
var path = require('path'),
express = require('express'),
bodyParser = require('body-parser');
module.exports = function(app) {
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser({
uploadDir:path.join(__dirname, 'public/upload/temp')
}));
return app;
};
In server.js
var express = require('express'),
config = require('./configure'),
app = express();
bodyParser = require('body-parser');
app = config( app );
app.post('/about', function( req, res ) {
console.log(req.body.message);
res.send( 'Hello World' );
});
app.listen( 3000, function () {
console.log('Server up: http://localhost:' + 3000);
});
TypeError: Cannot read property 'Store' of undefined
at new module.exports (/home/dickens/Desktop/node-login/node_modules/connect-mongo/src/index.js:58:50)
at Object. (/home/dickens/Desktop/node-login/app.js:56:14)
change directory of your index.js in the (/home/user/your-app/node_modules/connect-mongo/src/index.js:58:50)

Node.js + express: specify routes

In my understanding, the way to serve views is to do the following:
app.set('view engine', 'ejs'); // or jade or whatever
app.set('views', __dirname + '/views'); // specify where to find the view files e.g. index.ejs
app.get("/", function(req, res) { res.render('index') });
However, when I check the code here https://github.com/jedireza/drywall/ , which is a boilerplate for node user management, I don't see any routes defined in app.js. But it works fine and if I type the url /signup in browser it will render signup.jade.
Which part, or which middleware is doing the magic of routing?
app.js content:
'use strict';
//dependencies
var config = require('./config'),
express = require('express'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
session = require('express-session'),
mongoStore = require('connect-mongo')(session),
http = require('http'),
path = require('path'),
passport = require('passport'),
mongoose = require('mongoose'),
helmet = require('helmet'),
csrf = require('csurf');
//create express app
var app = express();
//keep reference to config
app.config = config;
//setup the web server
app.server = http.createServer(app);
//setup mongoose
app.db = mongoose.createConnection(config.mongodb.uri);
app.db.on('error', console.error.bind(console, 'mongoose connection error: '));
app.db.once('open', function () {
//and... we have a data store
});
//config data models
require('./models')(app, mongoose);
//settings
app.disable('x-powered-by');
app.set('port', config.port);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
//middleware
app.use(require('morgan')('dev'));
app.use(require('compression')());
app.use(require('serve-static')(path.join(__dirname, 'public')));
app.use(require('method-override')());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(config.cryptoKey));
app.use(session({
resave: true,
saveUninitialized: true,
secret: config.cryptoKey,
store: new mongoStore({ url: config.mongodb.uri })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(csrf({ cookie: { signed: true } }));
helmet(app);
//response locals
app.use(function(req, res, next) {
res.cookie('_csrfToken', req.csrfToken());
res.locals.user = {};
res.locals.user.defaultReturnUrl = req.user && req.user.defaultReturnUrl();
res.locals.user.username = req.user && req.user.username;
next();
});
//global locals
app.locals.projectName = app.config.projectName;
app.locals.copyrightYear = new Date().getFullYear();
app.locals.copyrightName = app.config.companyName;
app.locals.cacheBreaker = 'br34k-01';
//setup passport
require('./passport')(app, passport);
//setup routes
require('./routes')(app, passport);
//custom (friendly) error handler
app.use(require('./views/http/index').http500);
//setup utilities
app.utility = {};
app.utility.sendmail = require('./util/sendmail');
app.utility.slugify = require('./util/slugify');
app.utility.workflow = require('./util/workflow');
//listen up
app.server.listen(app.config.port, function(){
//and... we're live
});
The routes are being added here:
//setup routes
require('./routes')(app, passport);

Resources