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 likewww
(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 | router.get('/', (req, res) => { |
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 | app.all('/secret', (req, res, next) => { |
Route handlers
Express allows multiple function callbacks at onee time, nevertheless please ensure that a next
object is included in both the subsequent function and the route handler itself. For example:
1 | const cb0 = function (req, res, next) { |
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.