Full series: Building website with Nodejs - A post from my experience
Previous post: Nodejs - Express with ejs/stylus basics
Middleware
Simply, middleware are just functions for handling requests from client. Each request can have be associated with a stack of middleware. That means when you have several of handler functions associated with one request, they will be executed sequentially. Back to the example from my previous post
In this example, there is only one middleware (handler) function for the GET
request to /
. Now we will add one more middleware, or maybe more if you want
You can also signal an error by passing it to the first argument of next()
function
Middleware can be used for several purposes such as authentication and authorization. You can follow the link to the full series at the beginning of this post and find the post that I wrote about authentication in Express. Middleware can also be used in setting common variables for displaying in layout (refer to the next section).
Layout in Express EJS
For Express 3.x, if you want to use layout, you need to install ejs-locals.
In the app.js
file, add these 2 lines before app.set('view engine', 'ejs');
Open the views folder, create a file named layout.ejs
There is nothing special here except the <%- body %>
tag. It’s the place
holder and will be replaced by the content of the page that uses this layout.
Next, create another page to consume this layout, for example, index.ejs
There is one problem with the layout. That is when you want to render a variable
in the layout using <%= varName %>
. Continue with the above example, if there
is a variable named varName inside layout.ejs
and you want it to display
based on the page that you are viewing, you can not pass the variable through
the the render function normally like this
You will get the error that varName is not defined because the variable is only
available inside the index.ejs
view, not the layout. To display it in the
layout, you need to assign it to res.locals
And then in layout.ejs
just echo the variable normally
For convenience, you can create a middleware to set common values (current logged in user for instance) and pass it to the routing function.