Marcus Node Bits - Express is best without generators

· February 7, 2014

I’m writing down some of the things I’ve picked up when I started to learn about NodeExpress and Mongo. Here are all the post in the series:

This post is about the most commonly used web framework in Node: Express. Node in itself is pretty cool and the three-line web server is mind blowing at first sight. Pretty soon though you want something that is a bit friendlier to code against. Most people seems to go with Express. From their web page we read:

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.

Couldn’t agree more. The only thing is… most tutorials on Express uses the generators. That is the set of tools that comes with Express (install with npm install express -g) and you’ll have the generators all over. This site generator bothers me in two ways:

  • it sets up a complete site, when I just want to do an API
  • that site defaults to server-side generation, when I want to serve a static JavaScript client

Nowadays I tend to default to a simple backend API (see, I din’t even write REST API just to avoid religious battles. Smooth operator :)), that just serve JSON and then a Javascript client that calls into that API, using AngularJS for example.

I don’t need Jade, Sessions and folders for controllers etc. My whole API will be 1-5 files depending on how modular I’m feeling. I might need a public folder but that’s easy enough to fix.

So my suggestion is that you ditch the generators (powerful as they are) and drop down to bare-bones Express. You’ll find a very powerful and terse framework that resembles NancyFx a lot. Ah, well it resembles Sinatra too, but Nancy is cooler.

In fact, on their guide-page, ExpressJs is showing you the minimal version first. And we can write the ubiquitous fit-in-a-tweet-web application:

This little application just responds with "Hello World" when you access it on [http://localhost:3000](http://localhost:3000/) ### Understanding Express The API for Express is very easy and in fact there just a couple of basic things that you need to know in order to start coding up an API. Things are considerable easier when we're just dishing out JSON rather than keeping creating a complete site. As always this is just the things that I've used and get to know. You should check out the API documentation, it's great. And the starting guide is also nice. First and formost you should create an Express application. This is super simple since that's what the express() function returns. Like this: In the little tweet example above you saw the app.get() function in action. The really good news is that all the HTTP verbs act in the same manner. They take an URL path and a callback function. You can understand it as: "when somebody *Posts* to '/orders/', execute this function that I'm writing here". As I said the path parameter can contain parameters that we easily get hold of via the req.params property. Here's an example of a get to an URL with a parameter, called id Often your clients will be sending data in the body of the HTTP request. Express provides an easy way to extract those by using the middleware bodyParser() (see below). Which gives us this easy way to access the body data To this you can post a HTTP form like this (using the awesome Postman extension for Chrome):
Sometimes, or rather after awhile, writing the functions inline gets a bit messy. You can then write the handling code in a separate module and include that. Express, default, puts these in a folder called "routes", but we can do as we want. Note that I'm using the exports-keyword in the userHandler.js file. That let's the function be visible to other modules. I used the name handler as a nod to a way we created frameworks in the 90-ies. Everything that we really didn't know what to name was "handler". It should maybe have been "controller" in this case... You return data via the response-object that is passed to the callback function for your route, often called res but you can of course name it what ever you want. The simplest is just to do send as we seen a lot of examples of already. When you send JSON back there's a special method for that. The content-type will automatically be set to "application/json" for you when using this method as a nice little service to you. ### Middleware At the heart of Express is the Connect middleware. For the most part you don't need to care about Connect since it's nicely exposed as a couple of functions, but it's really how Express is stitched together. We have already seen the bodyParser() in action and here are few others that I found useful: #### basicAuth
basicAuth()- sets up basic authentication for your site. As always, basic is sending the username and password in clear text, so beware. #### directory and static directory() - that helps you configure directories, together with static() it can help you to serve up static files; like your client side JavaScript application for example #### app.param() - an example of middleware, that is really powerful The one middleware that impressed me the most, so far, is app.param(). This can help you do some really powerful stuff, in just a few lines of code. To show this I'm going to lean on an example from this site and walk your through it: You could also do hard coded paths, of course (like /users) and create a little snippet that loads users by id. This is shown to great effect in the documentation for app.param() and I've adapted it here: ### Conclusion Yeah, as you can see express is not that hard and that the same time powerful. Just like we like it. I think you get the know the framework much better without the generators. Go old school and type it yourself!

Twitter, Facebook