The Express, path and other modules are loaded via require ()
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 ');
Index.js and Users.js routing files under the Routes folder are loaded via require ()
var routes = require ('./routes/index ');
var users = require ('./routes/users ');
Generate an Express instance app
var app = Express ();
View Engine Setup
Set the Views folder to the directory where the view files are stored, that is, where the template files reside; __dirname is a global variable that stores the directory where the currently executing script resides
App.set (' Views ', Path.join (__dirname, ' views '));
Set the view template engine to Ejs
App.set (' View engine ', ' Ejs ');
Uncomment after placing your favicon in/public
Set/public/favicon.icon to Favicon icon
App.use (Favicon (Path.join (__dirname, ' public ', ' Favicon.ico '));
Load Log Middleware
App.use (Logger (' dev '));
Loading middleware for parsing JSON
App.use (Bodyparser.json ());
Loading middleware for parsing urlencoded request body
App.use (bodyparser.urlencoded ({extended:false}));
Loading middleware for parsing cookies
App.use (Cookieparser ());
Set the public folder to a directory where static files are stored
App.use (Express.static (Path.join (__dirname, ' public '));
Routing Controller
App.use ('/', routes);
App.use ('/users ', users);
Catch 404 and forward to error handler
404 errors are captured and forwarded to the error handler
App.use (function (req, res, next) {
var err = new Error (' not Found ');
Err.status = 404;
Next (ERR);
});
Error handlers
//Development Error Handler
//will print StackTrace
//Bug handler in the development environment, render error messages to the wrong template and display to the browser
if (App.get (' env ') = = = ' Development ') {
App.use (function (err, req, res, next {
Res.status (Err.status | |);
Res.render (' error ', {
message: Err.message,
Error:err
Production Error Handler
No stacktraces leaked to user
Error handler in the production environment, rendering error messages to the wrong template and displaying them in the browser
App.use (function (err, req, res, next) {
Res.status (Err.status | | 500);
Res.render (' Error ', {
Message:err.message,
Error: {}
});
});
Exporting an app instance for other modules to call
Module.exports = app;
Code comments for default app.js in the Express4.10.2 development framework