Express.js FUNdamentals: An Essential Overview of Express.js

Courses on Node.js, React
and JavaScript
Become an expert with my comprehensive
Node.js, React.js and JavaScript courses.
Learn Full Stack Javascript →


Note: This text is a part of upcoming ebook JavaScript and Node FUNdamentals: A Collection of Essential Basics.

Express.js is an amazing framework for Node.js projects and used in the majority of such web apps. Unfortunately, there’s a lack of tutorials and examples on how to write good production-ready code. To mitigate this need, we released Express.js Guide: The Comprehesive Book on Express.js. However, all things start from basics, and for that reason we’ll give you a taste of the framework in this post, so you can decide if you want to continue the learning further.

Express.js Installation

Assuming you downloaded and installed Node.js (and NPM with it), run this command:

$ sudo npm install -g express@3.4.3

Express.js Command-Line Interface

Now we can use command-line interface (CLI) to spawn new Express.js apps:

$ express -c styl expressfun
$ cd expressfun && npm install
$ node app

Open browser at http://localhost:3000.

Here is the full code of expressfun/app.js if you don’t have time to create an app right now:

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Routes in Express.js

If you open the expressfun/app.js, you’ll see two routes in the middle:

...
app.get('/', routes.index);
app.get('/users', user.list);
...

The first one is basically takes care of all the requests to the home page, e.g., http://localhost:3000/ and the latter of requests to /users, such as http://localhost:3000/users. Both of the routes process URLs case insensitively and in a same manner as with trailing slashes.

The request handler itself (index.js in this case) is straightforward: every thing from the HTTP request is in req and write results to the response in res:

exports.list = function(req, res){
  res.send("respond with a resource");
};

Middleware as The Backbone of Express.js

Each line above the routes is a middleware:

app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

The middleware is a pass thru functions that add something useful to the request as it travels along each of them, for example req.body or req.cookie. For more middleware writings check out Intro to Express.js: Parameters, Error Handling and Other Middleware.

Configuration of an Express.js App

Here is how we define configuration in a typical Express.js app:

app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

An ordinary settings involves a name (e.g., views) and a value (e.g., path to the folder where out templates/views live). There are more than one way to define a certain settings, e.g, app.enable for boolean flags.

Jade is Haml for Express.js/Node.js

Jade template engine is akin to Ruby on Rails’ Haml in the way it uses whitespace and indentation, e.g., layout.jade:

[Sidenote]

Reading blog posts is good, but watching video courses is even better because they are more engaging.

A lot of developers complained that there is a lack of affordable quality video material on Node. It's distracting to watch to YouTube videos and insane to pay $500 for a Node video course!

Go check out Node University which has FREE video courses on Node: node.university.

[End of sidenote]

doctype 5
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    block content

Other than that, it’s possible to utilize full-blown JavaScript code inside of Jade templates.

Conclusion About The Express.js Framework

As you’ve seen, it’s effortless to create MVC web apps with Express.js. The framework is splendid for REST APIs as well. If you interested in them, visit the Tutorial: Node.js and MongoDB JSON REST API server with Mongoskin and Express.js and Intro to Express.js: Simple REST API app with Monk and MongoDB.

If you want to know what are the other middlewares and configurations, check out Express.js API docs, Connect docs and of course our book — Express.js Guide. For those who already familiar with some basics of Express.js, I recommend going through ExpressWorks — an automated Express.js workshop.

Courses on Node.js,
React and JavaScript
Become an expert with my comprehensive
Node.js, React.js and JavaScript courses.
Learn Full Stack Javascript →

--
Azat Mardan
Azat Mardan avatar
https://www.linkedin.com/in/azatm
To contact Azat, the main author of this blog, submit the contact form.

Also, make sure to get 3 amazing resources to FREE when you sign up for the newsletter.
Simple.
Easy.
No commitment.

6 thoughts on “Express.js FUNdamentals: An Essential Overview of Express.js

  1. Pingback: ExpressJS FUNdamentals: An Essential Overview of ExpressJS | Dinesh Ram Kali.

  2. Pingback: Express.js Fundamentals - Modern Web

  3. Pingback: Expressjs - Khai's personal knowledge vault.

  4. Pingback: Node.js FUNdamentals: A Concise Overview of The Main Concepts | webapplog: Full-Stack Software Engineering

Leave a Reply

Your email address will not be published. Required fields are marked *