Understanding ExpressJs, a Node.js framework

Hashir Hussain
9 min readNov 9, 2017

--

I’ve gathered some useful resources intended to help you for better understanding in Express.js.This is aimed at people who have some familiarity with Node.js. To know how to run Node scripts and can install packages with npm you don’t have to be an expert, though — I promise.

Warm Up

Ok! lets start,

Express.js is a web framework which is based on the core Node.js http module and Connect components. Those components are called middlewares. They are the cornerstone of the framework’s philosophy, i.e., configuration over convention.
Like any abstraction, Express hides difficult bits and says “don’t worry, you don’t need to understand this part”. It does things for you so that you don’t have to bother. In other words, it’s magic. You might not understand the inner workings of Express. This is like driving a car; I drive a car just fine without intimate knowledge of its workings, but I’d be better off with that knowledge. What if things break? What if you want to get all the performance you can out of the car? What if you have an insatiable thirst for knowledge?
Bored?? Okay Okay, so let’s move to some practicals and understand Express.js.

I’m considering Express.js is a piece of cake.

ExpressJs , Piece of cake

So let’s understand Express from the bottom, with Node.

Bottom layer: Node’s HTTP server

Let’s start by creating a web server in Node.Js.
Node has an HTTP module which makes a pretty simple abstraction for making a web server.
How? Like this example:
Create a js file and copy the below code.

// Require http module
var http = require("http");

// Build the server
var app = http.createServer(function(request, response) {
response.writeHead(200, {
"Content-Type": "text/plain"
});
response.end("Hello world!");
});

// Start that server
app.listen(3000, "localhost");
console.log("Server running at http://localhost:3000");

Start your server node <filename>and check the output. You’ll get a response of “Hello world!”

if you visit localhost:3000/in your browser. You’ll get the same response no matter what, too. You can try visiting localhost:3000/mango or localhost:3000/?fruit=mango, and it’s like talking to a brick wall: “Hello world!”

Builtin require function is the easiest way to include modules that exist in separate files. The basic functionality of require is that it reads a JavaScript file, executes the file, and then proceeds to return the exports object.

hmm…, that means:

  1. The first line used the require function to load a built-in Node module called http. It puts this fabulous module inside of a variable called http
  2. Then we put a server in a variable called appby using http.createServer. This takes a function that listens for requests. (I’ll explain this in a minute because they’re Super Duper Important. Skip over it for now.)
  3. The last thing we do is telling the server to listen for requests coming in on port 3000, and then we just log that out. And then we’re up.

Okay, back to the skipped part the request handler function

The request handler

I should say that there’s a bunch of cool HTTP stuff in here that I don’t think is relevant to learning Express. If you’re interested, you can look at the docs for the HTTP module because they have a bunch of stuff.

Whenever we make a request to the server, that request handler function is called. If you don’t believe me, try putting a console.login there. You’ll see that it logs out on your terminal every time you load a page.

request is a request that comes from the client. In many other apps, you’ll see this shortened to req. Let’s look at it. To do that, we’ll modify the above request handler a bit:

// Build the server
var app = http.createServer(function(request, response) {

// Build the result
var result = "";
result += "Request URL: " + request.url + "\n";
result += "Request type: " + request.method + "\n";
result += "Request headers: " + JSON.stringify(request.headers) + "\n";

// Send result
response.writeHead(200, { "Content-Type": "text/plain" });
response.end(result);
});

Restart and reload localhost:3000

You’ll see what URL you’re requesting, that it’s a GETrequest, and that you’ve sent a number of cool headers like the user-agent and more magical HTTP stuff! If you visit localhost:300/honey, you’ll see the request URL change. If you visit it with a different browser, the user-agentwill change. If you send it a POSTrequest, you’ll see the method change.

Node.js applications are stored in memory, and if we make changes to the source code, we need to restart our app.

The responseis the next part. Just like the prior argument is often shortened, this is often shortened to the three-letter res. With each response, you get the response all ready to send, and then you call response.end. Eventually, you must call this method; even the Node docs say so. This method does the actual sending of data. You can try making a server where you don’t call it, and it just hangs forever.

Before you send it out, you’ll want to write some headers. In our example, we do this:

response.writeHead(200, { "Content-Type": "text/plain" });

This does two things. First, it sends HTTP status code 200, which means ”OK, everything is good”. Then, it sets some response headers. In this case, it’s saying that we’re sending back the plaintext content-type. We could send other things like JSONor HTML.

Alright, if you thirst for more you could do something like this.

// Build the server
var app = http.createServer(function(request, response) {

// Homepage (Default)
if (request.url == '/') {
response.writeHead(200, { 'Content-Type': 'text/html'});
response.end("<h1>Welcome to the homepage!</h1>");
}

// About page
else if (request.url == '/about') {
response.writeHead(200, { 'Content-Type': 'text/plain'});
response.end('Welcome to the about page!');
}

// 404'd!
else {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.end('404 error! Page not found.');
}
});

Middle layer: Middle Wares

Using Express.js:

Middleware is a special function that allows for better code organization and reuse. Some of the middleware is packaged as third-party (NPM) modules and can be used right out of the box. Other times, we can write our own custom middleware. In both cases the syntax is app.use().

Okay, let’s have a explanation by this code.

Let’s say we wanted to write the “hello world” app that we had above, but with Express this time. Don’t forget to install Express npm install express. Once you’ve done that, the app is pretty similar.

// Require the ingredients we need
var express = require("express");
var http = require("http");

// Build the app
var app = express();

// Add some middleware
app.use(function(request, response) {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Hello world!");
});

// Start it up!
http.createServer(app).listen(3000);

So let’s step through this.

First, we require Express. We then require Node’s HTTPmodule just like we did before. We’re ready.

Then we make a variable called applike we did before, but instead of creating the server, we call express(). What’s going on? What is this madness?

We then add some middleware — it’s just a function. We pass this to app.use, and this function looks an awful lot like the request handlers from above.

Then we create the server and start listening. http.createServer, took a function before, so guess what — appis just a function. It’s an Express-made function that starts going through all the middleware until the end. But it’s just a request handler like before.

Worth noting that you might see people using app.listen(3000), which just defers to http.createServer. That’s just a shorthand.

In my language Middlewares are ‘Just a request handlers’ that starts from the top to the next, and to the next, and so on.

Here’s what middle ware basically looks like:

function IamFuncMiddleware(request, response, next) {
// Do stuff with the request and response.
// When we're all done, call next() to defer to the next middleware.
next();
}

When writing your own middleware, don’t forget to call the next()callback function. Otherwise, the request will hang and time out.

When we restart our server, we start at the topmost middleware and work our way to the bottom. So if we wanted to add simple logging to our app, we could do it!

var express = require("express");
var http = require("http");
var app = express();

// Logging middleware
app.use(function(request, response, next) {
console.log('%s %s — %s', (new Date).toString(), request.method, request.url);
next();
});
// Homepage
app.use(function(request, response, next) {
if (request.url == "/") {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Welcome to the homepage!\n");
// The middleware stops here.
} else {
next();
}
});

// About page
app.use(function(request, response, next) {
if (request.url == "/about") {
response.writeHead(200, { "Content-Type": "text/plain" });
response.end("Welcome to the about page!\n");
// The middleware stops here.
} else {
next();
}
});

// 404'd!
app.use(function(request, response) {
response.writeHead(404, { "Content-Type": "text/plain" });
response.end("404 error!\n");
});

http.createServer(app).listen(3000);

If you run this app and visit localhost:3000, you’ll see that your server is logging some stuff and you’ll see your pages.

While you can totally write your own, there’s a ton of middleware out there. Let’s remove our logger and use Morgan, a nice logger for Express. Simply do npm install morgan

Top layer: Routes

We’ve finally arrived at top layer of our piece of cake. Ohh.. the middle layers on soft and spongy bottom layer was too delicious.

Routing is a way to map different requests to specific handlers. In many of the above examples, we had a homepage and an about page and a 404 page. We’d basically do this with a bunch of if statements in the examples.

But Express is smarter than that. Express gives us something called “routing” which I think is better explained with code than with English:

var express = require("express");
var http = require("http");
var app = express();

app.all("*", function(request, response, next) {
response.writeHead(200, { "Content-Type": "text/plain" });
next();
});

app.get("/", function(request, response) {
response.end("Welcome to the homepage!");
});

app.get("/about", function(request, response) {
response.end("Welcome to the about page!");
});

app.get("*", function(request, response) {
response.end("404!");
});

http.createServer(app).listen(3000);

ooh. That’s looks more tasty.

Routes can be either good old web pages or REST API endpoints. In both cases the syntax is similar: we use app.<VERB()>, where VERB()is an HTTP method such as GET, POST, DELETE, PUT, OPTIONS, or PATCH.The first argument is a path, like /about or /. The second argument is a request handler similar to what we’ve seen before.

The browser makes a GET request when you navigate it to some page, so at the very least your server should process GET requests.

These routes can get smarter, with things like this:

app.get("/fruit/:which", function(req, res) {
res.end("My favorite fruit is, " + req.params.which+ ".");
// Fun fact: this has security issues
});

Restart your server and visit localhost:3000/fruit/mango for the following message:

However, starting with Express.js v4.x, using the new Router class is the recommended way to define routes, via router.route(path).

The router.route(path) method is used to chain HTTP verb methods. For example, in a create, read, update, and delete (CRUD) server that has POST, GET, PUT, and DELETEendpoints for the /fruit/:which URL (e.g.,/fruit/mango), we can use the Router class as follows:

var express = require('express');
var router = express.Router();
router
.route('/fruit/:which')
.all(function(request, response, next){
// This will be called for request with any HTTP method
})
.post(function(request, response, next){
//do something
})
.get(function(request, response, next){
//do something
})
.put(function(request, response, next){
//do something
})
.delete(function(request, response, next){
//do something
});

Request handler in express way:

Request handlers in Express.js are strikingly similar to callbacks in the core Node.js http.createServer() method,Because they’re just functions (anonymous, named, or methods) with req and res parameters.

Like:

var ping = function(req, res) {
console.log('ping');
res.end(200);
};
app.get('/', ping);

In addition, we can utilize the third parameter, next(), for control flow. Here is a simple example of two request handlers,
zig and zag where the former just skips to the latter after printing a word zig

var zig = function(req, res, next) {
console.log('zig');
return next();
};
var zag = function(req, res) {
console.log('zag');
res.end(200);
};
app.get('/', zig,zag);

When a request comes on the / route, Express.js calls zig(), which acts as middleware in this case (because it’s in the middle!). Zig, in turn, when it’s done, calls zagwith that finished response with res.end().

So, that’s all to create our very very simple home made ExpressJs cake. But of course this is not enough to make you a perfect chef. So keep on searching, practicing, exploring and that makes you the world famous Master Chef. :)

Reach out me with your queries, suggestions and feedback.

--

--