Saturday, March 3, 2018

Exploring Express.js Features

Express.js comes with lot of feature ,lets explore them step by step

what is res.locals in express.js ?

    An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any).
    This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.
        app.use(function(req, res, next){
          res.locals.user = req.user;
          res.locals.authenticated = ! req.user.anonymous;

what is app.locals in express.js ?

    The app.locals object has properties that are local variables within the application.Once set, the value of app.locals properties persist throughout the life of the application.You can access     local variables in templates rendered within the application. This is useful for providing helper functions to templates, as well as application-level data. Local variables are available in         middleware via
        app.locals.title = 'My App';
        app.locals.strftime = require('strftime'); = '';
    in contrast with res.locals properties defined in app.locals are valid only for the lifetime of the request.

How to remove 'x-powered-by' header:
    to remove certain header you can use 'res.removeHeader' using a custom middleware or can use 'app.disable'.
        app.use(function (req, res, next) {



    try to hit some route say GET for simplicity in POSTMAN and check below header is present on response
        X-Powered-By →Express

How to enable case-sensitive routing:Inside our router definition we can pass 'caseSensitive=true'
    var router = express.Router({
      caseSensitive: true

    other approach described below,but found to be not working
    app.disable('case sensitive routing',false);

    by making route case-sensitive we end up in /login is not same as / you will get 404 for /LOGIN if you defined only /login

Unhandled error:
     In express router if we get an error and its not handled then it trickle to app level.

consider below route

router.get('/uncaught', function (req, res,next) {
  var Promise = require('bluebird');
  var Pgb = require("pg-bluebird");
  var pgb = new Pgb();
  var connectionString = 'postgres://xdba:sangram@localhost:5432/xplay';
  var cnn;

  var query1 = 'select * from tbl_nowhere where channel_id=1';
  return pgb.connect(connectionString)
    .then(function (connection) {
      cnn = connection;
      return cnn.client.query(query1);
    }).then(function (result) {
      return result;
    .catch(function (error) {
      throw error;

we are purposefully giving wrong table name in query so that we get an error 'relation "tbl_nowhere" does not exist'.

when I am throwing an error in catch block it has been observed that request does not halt,now let's replace 
'throw error' by 'next(error)'.

Now error trickle down to app.js.To catch this unhandled error express.js uses middleware.usually at bottom of is how it looks like.

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

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

what it does is check if application is running in developement mode or not,if it is running in development mode then it loads error view with message & stacktrace.
On production enviornment we usually don't show such errors to client but log them somewhere and show some generic error to user.

No comments:

Post a Comment