What's up coder!

All you need about Express.js - 1

Word count: 433Reading time: 2 min
2025/03/22
loading

Express.js


In this post, we will take a first sip of what is going on with an Express.js program. Starting from its basic directory, the definition and functionality of each files will be discussed. Then we will look into the routing function, including defining a route path and specifying route handler.


Root directory

  • app.js: used to configutr Express server, define middleware, and routes.

  • package.json(core of a Node.js program): contains program details(e.g., name, version), dependencies, scripts, other configurations.

  • bin/: contains executable files like www(defining how to initiate server).

Core directory

  • public/: used to keep static file like CSS, JS, Images.

  • routes/: define routes, handling URL requests.

    • index.js: define the homepage route(/).

    • users.js: define user-related route(/users).

  • views/: keeps view templates

Route methods

Under of the assumption of the existence of the express and app instance, Express provide the routing functionality in the form of:

1
2
3
router.get('/', (req, res) => {
res.send('hello world')
})

The roouter.METHOD()supports all HTTP request methods. Please refer to official documentation for further details.

The special routing method app.all() enables middleware functions whenever a HTTP request is called.

1
2
3
4
app.all('/secret', (req, res, next) => {
console.log('Accessing the secret section ...')
next() // pass control to the next handler
})

Route handlers

Express allows multiple function callbacks at onee time, nevertheless please ensure that a nextobject is included in both the subsequent function and the route handler itself. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const cb0 = function (req, res, next) {
console.log('CB0')
next()
}

const cb1 = function (req, res, next) {
console.log('CB1')
next()
}

app.get('/example/d', [cb0, cb1], (req, res, next) => {
console.log('the response will be sent by the next function ...')
next()
}, (req, res) => {
res.send('Hello from D!')
})

Others

Up to this point, you might wonder now where I should write the code that will exactly handle the request and perform business logic?

Technically, developers are allowed to write code directly within the route module, just the like the examples above. However, it is the least recommended thing to do, as the program grow, the organizatioin and clarity of the code tends to be a giant mess. In this case, it is strongly advised to seperate the code into three layers, including routing, controller and service. Routing account for directing requests to where it should be. Controller addresses the requests before they are forwarded to service for program executition.

CATALOG
  1. 1. Express.js
    1. 1.1. Root directory
    2. 1.2. Core directory
    3. 1.3. Route methods
    4. 1.4. Route handlers
    5. 1.5. Others