Evolution of a Node.js API, Zoe.js — Express.js

Adams Academy
3 min readJul 17, 2020

--

Express.js is Node.js package which provides a thin layer for building web applications.

Fast, unopinionated, minimalist web framework for Node.js

Installation happens with npm:

npm install express

Web server

Building a web server with Express.js is a piece of cake. You get Routing ( app.get('/', ...)) by default, you don't have to the check the URLs manually, you immediately create routes to specific URLs. get refers to the HTTP's GET method, what we discuss later, in another chapter. listen command starts the server on port 9000, and there is an optional callback function when the server is started.

Start the server with node server.js.

Middlewares

Middlewares are middle layers in the application’s Request-Response cycle. A request comes into the application, then business logic runs and finally the response sends back to the user.

Using a Middleware makes you capable of modifying both the Request and the Response. Your application might have multiple Middlewares and these Middlewares don’t have to run in every case. If you call the next() function then you call the next Middleware, but if you don't, then the Request-Response cycle ends there.

Middlewares are callbacks registered with app’s usemethod. Logging middleware runs first, it writes the Request URL and Method to the console. Then next() function calls the next Middleware, the Authentication middleware. It has a random logic, which either ends (doesn't call next()) the Request-Response cycle with Unauthorized status or adds the loggedInUser object to the request object and calls the next Middleware. Finally, the router callback gives a json response about the user.

Middlewares have many typical use cases:

  • Authentication
  • Logging
  • Error handling
  • Rate-limiting
  • CORS handling

Error handling middleware

Express.js comes with a default Error handler middleware, the only difference between the original middleware and this one is that this has an additional err parameter:

You have to declare your Error handler middleware as the last middleware, otherwise it doesn’t get called. If you need multiple error handlers (e.g. separate error logging middleware) you can call the next() function here as well.

Article Series

This article (Chapter 3) is part of the Zoe.js article series. Below you can find the Next chapter and all the available Chapters.

--

--

Adams Academy

Adams Academy helps you to cut through the noise and understand programming languages, web development with simple programming tutorials.