Getting Started with Expressjs

Tweet about this on TwitterShare on LinkedIn0Share on Google+0Share on Reddit0Buffer this pageFlattr the authorEmail this to someonePrint this page

Getting Started with Expressjs

This post is targeted at Express 3.x and *nix system, however the concepts are same across all OS for Express 3.x.

Windows users, please refer to the comment by acveer.

Once you are done with post, you can refer this post to see what has changed in Express 4.x

You can use Slush Express Generator to scaffold an Express 4 app, to be consistent across OS.

Express js

Express is a minimal and flexible node.js web application framework, providing a robust set of features for building single and multi-page, and hybrid web applications.

Expressjs is a server side framework, that takes care of handling requests and responses. It can use templating engines like Hogan (derived from HandleBars), Jade, ejs or CSS preprocessors like LESS, Stylus.

If you have worked with any web based Node projects earlier you must have seen a lot of them would be using Express. Because that is what Expres does to your Node app.

Contents

Setup Express

So lets get started. First we would install Node. You can find help here. Then we will install Express using NPM.

Windows Mac/*nix
npm install -g express    sudo npm install -g express

Easy Peasy!! Once this is done, we will scaffold a new app using express template. So lets create a new folder  mkdir myExpressApp & then  cd myExpressApp.

PS: Jade is the default templating engine & css is the default style sheet.

PS: Express itself supports many templating engines. The scaffold-er/generator only supports the listed. You can generate a sample app & add your own templating engines or CSS preprocessors to it.

Next, lets create a new express app. Run  express myFirstExpressApp. Bam!! This will result in something like this

Screen Shot 2014-03-09 at 3.42.39 PMNow, we will install the dependencies. Run  cd myFirstExpressApp && npm install. This will CD into myFirstExpressApp & run npm install. After the install is completed, this will result in a folder structure like

Screen Shot 2014-03-09 at 3.45.23 PMWell to be honest, I am not really a Jade fan! I am more comfortable with Hogan. Personally, Jade kind of freaks me out with how one writes a HTML markup (no offence). You can open up any of the .jade files inside the views folder to check it out.

And when I worked with Jade, I had spent quite a lot of time indenting & cleaning up the .jade files. Instead, if you think you have a HTML markup document & want to convert it into a Jade template, you can use this tool (The convert button is at the bottom of the page).

Whatever templating language you use, the output on the page will be the same!. This is more of a developer or a client preference.

Express with Hogan & LESS

Now, Lets scaffold a Express app with Hogan as the templating engine & LESS as the stylesheet support language. Lets come back to our root folder myExpressApp ( cd ..). Then run  express myAwesomeExpressApp -H -c less & the result should be

Screen Shot 2014-03-09 at 4.01.42 PM

CD into the folder & run npm install  cd myAwesomeExpressApp && npm install. Your folder structure should be like this

Screen Shot 2014-03-09 at 4.07.16 PMNotice that we are using hjs for templating & less for stylesheets preprocessing. Now, lets dive into the file structure.

The first file we are going to take a look at is the package.json. Open it up in your favorite editor. (I am using Brackets, highly recommended. Quick intro about brackets here.) You can see the default values with our 3 dependencies – express, hogan & less. You can update your project name here if you want.

App.js walkthrough

Next, lets open up the app.js. This is where all our configs go in.

Screen Shot 2014-03-09 at 4.31.51 PMIf you are not familiar with the way Node does things, I would highly recommend reading this. If you do know, then you must have recognized the Commonjs module pattern. Where each piece of distinctive code is  written in a module & exported. This can be used in any other module, with the require keyword.

  • Line nos 6-10 – precisely does that.
  • Line 12, we create a new Express app.
  • Line 15-25 – we define the configs for express.
  • Line 15 – set the port, change this only if 3000 is used by another app on your machine.
  • Line 16 – by default, express expects its template files to be in the views folder. In case you have a different path, you can update it here.
  • Line 17 – The view engine is hjs. If you are using a different engine than the scaffolded, you can declare it here.
  • Line 18 – This will look for a favicon in your root folder. If it cannot find one, it will set the Expressjs favicon instead.
  • Line 19 – This will initiate the logger, if in dev mode.
  • Line nos 20-21 – They are a replacement for express.bodyParser() middleware. express.bodyParser() consists of express.json(), express.urlencoded() & express.multipart() middlewares. If you don’t want any of the middlewares like express.multipart(), you can use each of them individually, as its is scaffolded here.
  • Line 22 – This is for simulating the PUT & DELETE request. More info here.
  • Line 23 – Invokes the router
  • Line 24 – Hooks up the less-middleware. This will parse the less files in the stylesheets folder and generate the css file. As of today, it looks like app.use(require('less-middleware')({ src: path.join(__dirname, 'public') })); , it will get updated to   app.use(require('less-middleware')(path.join(__dirname, 'public'))); eventually.
  • Line 25 – This declares the location of the static resources, js, css & img files.
  • Line 28-30 – Initiates the error handler if in dev mode.
  • Lines 32-33 – Declares the routes to which our app will respond with the resources listed as the second argument. i.e. if the route is the base page (http://localhost:3000), express will go to the routes/index.js (defined in the require statement on line 7) & execute the index method.
  • Lines 35-37 – Creates a server & listens on the port specified.

PS: The order of loading middleware (using app.use()) is very critical. If you change the order, things might not work as expected. 

Next, lets open up index.hjs inside the views folder. Compared to jade, isn’t this a lot more “markup-ish”. This page expects an object/value for the title variable. Next open up the routes/index.js.

The index method takes in 2 arguments. The request (req) & the response (res). All the incoming data like url params or body payload in case of post can be found inside the req object. And res is for sending data back. This is what we are going to do now. We will ask express to render a response. look for a index template inside the routes folder, take in the second argument as an object literal/model & build a markup & dispatch it to the client.

Run express app

So, lets test drive this app now. Back to prompt/terminal, run  node app.js. If you see an error message like

Please update your less-middleware usage 

Then it means that the express scaffolding template code is not updated to the latest less-middleware syntax. So go ahead and replace  app.use(require('less-middleware')({ src: path.join(__dirname, 'public') }));  with  app.use(require('less-middleware')(path.join(__dirname, 'public')));  on line 24. More info here.

If everything goes well, you should see a message in your terminal that says

Awesome! Now lets head to our browser and navigate to  http://localhost:3000/. You should see a Welcome to Express message. Remember routes/index.js, we have set the title to “Express”. Lets go ahead and change that whatever we want. I will change that to “My Awesome Express App” & save it. Back to prompt/terminal press control + C to stop the node server. Then run  node app.js to restart the server. Back to browser and refresh, this will update the message on the page!.

Do note that all the resources are served from the public folder.

Next, lets navigate to  http://localhost:3000/users, This is another route we have defined in the app.js. You should see a static message as written in routes/user.js list method.

Debugging Express

Instead of running your app like node app.js, you can run your app like DEBUG=express:* node app.js. This mode will be helpful while you are debugging your app. The messages and logging are a lot more verbose.

Must Have : Nodemon

Once you are in the thick of developing an Express app, you will find yourself making changes to your app.js or other files & going back to terminal to truncate the node server and restart it again. It will be fun at beginning, but.. you know.

For me its mostly laziness. So Nodemon (spelled as no-demon) to the rescue.Lets install nodemon, run

Windows Mac/*nix
npm install -g nodemon  sudo npm install -g nodemon

From now on we run nodemon app.js  instead of node app.js. So when you make changes to your js files, you can wait for the nodemon to restart the server for you. Then you can simply refresh the page. Swwweeet!!

Custom Error Handling

Lets take a look at custom error handling using express middleware. If there is an error on the server side, we can add our own custom middleware handler in our app.js as below

source

Enable, Enabled & Disable, Disabled Settings

Using express, you can enable & disable a setting in express in a simple way.

app.configure()

Express provides environment specific configurations as well. Lets say that you use a certain database for development, and another database for production. Simple option is to define the process.env as dev or prod and switch the connection strings. Or, use express to do this

Application settings

Express provides a few settings that can be customized. Some of the settings are

  • env Environment mode, defaults to process.env.NODE_ENV or “development”
  • trust proxy Enables reverse proxy support, disabled by default
  • jsonp callback name Changes the default callback name of ?callback=
  • json replacer JSON replacer callback, null by default
  • json spaces JSON response spaces for formatting, defaults to 2 in development, 0 in production
  • case sensitive routing Enable case sensitivity, disabled by default, treating “/Foo” and “/foo” as the same
  • strict routing Enable strict routing, by default “/foo” and “/foo/” are treated the same by the router
  • view cache Enables view template compilation caching, enabled in production by default
  • view engine The default engine extension to use when omitted
  • views The view directory path, defaulting to “process.cwd() + ‘/views'”

& you can use any of them using the app,use(); middleware method.

app.verb()

Verbs in other words are actions. Actions like get, put, delete etc.

app.all()

This method will be called irrespective of the request type. This is particularly useful, if you want authentication to happen before each method is invoked.

app.all('*', requireAuthentication)

or

app.all('/api/*', requireAuthentication);

Request, Response & Middleware

You can read more about Request object here, Response object here & Middleware here.


Thanks for reading! Do comment.
@arvindr21

Tweet about this on TwitterShare on LinkedIn0Share on Google+0Share on Reddit0Buffer this pageFlattr the authorEmail this to someonePrint this page
  • mutyalarao

    Thanks Arvind! I have just stumbled upon one of your posts today and read a lot of your articles in just one day. Thats says all about your content! I really appreaciate your lucid explanation of the concepts.

    However I have one doubt, request you to please clarify. Once I create a small web application using Node.js and Mongo db, how easily can I deploy it to another machine? Does it require setting up all the servers in the new machine or any method of one-click package and deployment?

    Thanks,
    Rao

  • vikas gupta

    Thanks a lot Arvind for th great post, It worked for me with some modification as mentioned by Acveer.

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Thanks Vikas, Glad it worked out.

  • Skattabrain

    This is a great post! Thanks for this.

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Thanks @Skattabrain:disqus!

  • acveer

    Thank You Aravind. Very good intro to expressjs.
    I was able to follow it fine on WINDOWS 7 with below changes :
    1)
    From Express 3.x onward’s, command line was migrated to a separate module: express-generator, so

    ‘npm install -g [email protected]
    worked for me instead of
    ‘npm install -g express’

    2)correspondingly, the express-generator moved the server creation code to ‘/bin/www; so

    ‘node ./bin/www’

    runs the app instead of ‘node app.js’
    &
    nodemon ./bin/www’

    • http://thejackalofjavascript.com/ Arvind Ravulavaru

      Hello acveer,

      Thanks for pointing out express-generator.
      If I am not wrong, you can scaffold the app with both ‘express-generator’ & ‘express -options’ as well. The output would be the same.

      Thanks,
      Arvind.

      • acveer

        You are probably correct. I just wanted list out that when installing express globally on windows, the command line did not work for me with ‘npm install -g express’. Yes it did install under App_Data/Roaming/npm/node_modules and set it under windows env. PATH, but there was no express.cmd for it to be available on the command line.

        using ‘npm install -g [email protected]′ made it available on the command line.

        • http://thejackalofjavascript.com/ Arvind Ravulavaru

          acveer,

          I got what you were saying now. :)

          I tested the same on my Windows machine and as you have mentioned, the express command is no more global.

          Thanks much for pointing it out. I will update this post. In the mean time, if you want to avoid this variation across OSs, you can use a slush express generator to scaffold your express app (https://www.npmjs.org/package/slush-express).

          Thanks,
          Arvind.