Express.js is an amazing framework for Node.js projects and used in a majority of Node-based web apps. Unfortunately, there’s a lack of tutorials and examples on how to write good production-ready code. To help mitigate this need, I released a book called Express.js Guide: The Most Popular Node.js Framework Manual. However, all things start from the basics, and for this post will give you a taste for the basics of the framework so you can decide if you want to continue the learning it further.
Installation
Assuming you downloaded and installed Node.js (and npm with it), run this command:
$ sudo npm install -g express@3.4.3
CLI
Now we can use command-line interface (CLI) to spawn new Express.js apps:
$ express -c styl expressfun $ cd expressfun && npm install $ node app
When this is complete, open your browser to https://localhost:3000
.
If you’d like to try a simple Express app, below is the full code of expressfun/app.js
(Note: going forward, as of v3.4.3, bodyParser is deprecated):
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
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 basically takes care of all the requests to the home page (e.g., https://localhost:3000/
) and the latter of requests to /users
, such as https://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 you write results to the response in res
:
exports.list = function(req, res){
res.send("respond with a resource");
};
Middleware
Each line above the routes in the code above 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')));
Middleware are 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 details on middleware, check out my prior post called Intro to Express.js: Parameters, Error Handling and Other Middleware.
Configuration
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 our templates/views live). There is more than one way to define certain settings, for example app.enable
for boolean flags.
Jade
The Jade template engine is akin to Ruby on Rails’ Haml in the way it uses whitespace and indentation. For example, let’s look at layout.jade
:
doctype 5
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
It’s possible to utilize full-blown JavaScript code inside of Jade templates.
Conslusion
Although we’ve barely scratched the surface, hopefully you can see how easy it is to create MVC web apps with Express.js. The framework works great for creating REST API’s as well. If you interested in using express for that purpose, check out my prior tutorials on 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 more about other middlewares and configurations, check out Express.js API docs, Connect docs and of course my 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.
This article was originally published at https://webapplog.com/express-js-fundamentals/
First off, thanks for writing this. At a front-end guy the term “middleware” has always been a little confusing to me, so it’s nice to see examples in code. For me, the problem with Express is the learning curve. I’ve found Sinatra a much more straightforward way to create end-points for a RESTful SPA, so it’s not a bad idea to lead readers toward some alternatives in case Express isn’t right for them.
Hi Josh,
Thank you for reading. You’re comment is interesting, because Express.js is modeled after the simplicity of Sinatra. 😉
This example is just what you get for a “classical” app that has pages. In case you need to build a REST API things are much easier (less configuration, middlewares, etc.). Take a look at my tutorials on https://webapplog.com and get the ultimate book on Express.js — https://expressjsguide.com.
PS: Middleware is just a function. Think about it as a callback/event handler in jQuery click or mouseup. 😉
The term “middleware” means different thing to different people. JavaScript peeps tend to refer to the *extra* things that happen between request and response (auth, caching, quotas, etc.) as middleware.
I’m learning express, too (IMO there is no substitute for node). One thing that helped me get started was realizing that it is a high-level abstraction. Which is a good thing if you want to move fast.