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);
Related
I want to render app.use('/', callback function) before rendering the static files from public folder.
Basically I am doing the authentication before accessing the website, so once it gets authenticated it should load the index.html (static file) from the public folder.
How should i do it?
I am using W3ID from IBM to authenticate the site.
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const WebAppStrategy = require("ibmcloud-appid").WebAppStrategy;
const CALLBACK_URL = "public/index.html";
var path = require('path');
var bodyParser = require('body-parser');
var port = process.env.VCAP_APP_PORT || 8080;
var mongoose = require('mongoose');
//var MongoStore = require('connect-mongo')(session);
const app = express();
// mongodb connection
mongoose.connect("mongodb://admin:admin123#ds261430.mlab.com:61430/events");
var db = mongoose.connection;
// mongo error
db.on('error', console.error.bind(console, 'connection error:'));
// parse incoming requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
// Set view engine as EJS
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// include routes
app.use(session({
secret: "123456",
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new WebAppStrategy({
tenantId: "73585f35-8d9c-4f6f-9ab2-d07ca0c1d371",
clientId: "863fce57-a717-4586-b8a2-0bf221ef4e68",
secret: "MzkxMTMxMWMtNmYxNi00ZjNhLWFiNzctZjFlM2NkMDM1ZTkz",
oauthServerUrl: "https://appid-oauth.eu-gb.bluemix.net/oauth/v3/73585f35-8d9c-4f6f-9ab2-d07ca0c1d371",
redirectUri: "https://csi.eu-gb.mybluemix.net/" + CALLBACK_URL
}));
passport.serializeUser(function(user, cb) {
cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
cb(null, obj);
});
app.get(CALLBACK_URL, passport.authenticate(WebAppStrategy.STRATEGY_NAME));
app.use('/',passport.authenticate(WebAppStrategy.STRATEGY_NAME), function(req, res) {`enter code here`
// do your authentication
});
// listen on port 8080
app.listen(port);
You can do this by just putting your app.use('/',...) above the app.use('/',express.static('...')).
Or
You can do this by passing option {index:false} to express.static like
app.use('/',express.static('path here',{index:false}));
This option will set express.static to not send the index.html by default.
I was trying to write some test which will emulate the post, but I have realised that nothing is posting. After further debugging, I realised that req.body is always undefined. Question is where did I make a mistake and how do I fix it. I seems that the problem is somewhere in the app.js file with order how the middleware loads but I can not figure it out where.
app.js
'use strict';
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const bodyParser = require('body-parser');
const fs = require('fs');
const session = require('express-session');
const redis = require('redis');
const mongoose = require('mongoose');
const redisStore = require('connect-redis')(session);
const client = redis.createClient();
const app = express();
const _UTILS = require('./application/_UTILS');
const db = JSON.parse(fs.readFileSync('/srv/webkb_mean/config/configFiles/database.json', 'utf8'));
mongoose.connect('mongodb://' + db['mongodb']['url'] + '/webKB-main');
mongoose.Promise = global.Promise;
app.use(session({
secret: _UTILS.getHashedValue(),
// create new redis store.
store: new redisStore({
host: 'localhost',
port: 6379,
client: client,
ttl: 36000
}),
saveUninitialized: false,
resave: false
}));
require('./config/router')(app);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(bodyParser.json())
app.use(express.static(path.join(__dirname, 'views')));
app.engine('html', require('ejs').renderFile)
// 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;
Your adding your bodyParser middleware to your server after you’ve added your routes. This is because express executes middleware(which includes routers since they are also middleware) in the order which they were added via .use().
Just move your router registration line:
require('./config/router')(app);
After your last middleware and before your 404 NOT FOUND handler.
app.engine('html', require('ejs').renderFile)
require('./config/router')(app);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
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');
});
My problem is that req.body becomes undefined when I try to render a page.
My app code:
var https = require('https');
var fs = require('fs');
var mongourl = "mongodb://localhost:27017/auntyinda";
var mongoose = require('mongoose');
fs.readdirSync(__dirname + '/models').forEach(function (filename) {
if (~filename.indexOf('.js')) require(__dirname + "/models/" + filename);
});
//var queries = require('./mongoq/query')
var express = require('express');
var path = require('path');
//var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var passport = require('passport');
var myPass = require('./security/auth')
var routes = require('./routes/index');
//var users = require('./routes/users');
var app = express();
var server = https.createServer({
cert: fs.readFileSync(__dirname + '/my.crt'),
key: fs.readFileSync(__dirname + '/my.key')
},app).listen(4000);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.configure(function(){
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//app.use(require('connect').bodyParser())
app.use(cookieParser());
app.use(expressSession( {
secret: process.env.SESSION_SECRET || 'sonic12',
resave: false,
saveUninitialized: false
}))
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
//});
mongoose.connect(mongourl)
//app.use('/', myPass);
app.use('/', routes);
//app.use('/users', users);
//app.locals.appdata = require("./data.json")
My route code:
router.post('/register', function(req, res, next) {
regcheck(req.body.username, req.body.password, req.body.passwordConfirm, function (error) {
if (error) {
console.log(req.body) //OUTPUT IS WHAT IS EXPECTED. NICE JSON FORMAT.
res.render('register', {
title: 'Register',
classname: 'register',
socialIcons: socialIcons,
isAuthenticated: false,
regdata: req.body,
err: error
})
}
})
})
I want the render to use the regdata object to refill data that was good back into the registration form. But for some strange reason it becomes undefined by the time it reaches the render.
My EJS file contains this line at the top:
<% console.log('Error recieved: '); console.log(err); console.log(regdata); %>
But the output of the console.log(regdata) is undefined. What is happening here? The err prints as it should. Thanks in Advance for your help.
Try this,
<pre><%= regdata %></pre>
I think you are missing out a = somewhere.
Consult the docs.
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.