The Express.js apps we have developed so far are just simply getting requests from users and sending matched message back to them. However, it is not what we want in the real web application.
In most case, we want to send back a relevant web page when our app receives request from user.
In order to do that, we need to npm install ejs file in the Express, create HTML page in the ejs file, and render HTMl from the ejs file.
I know it sounds confuse now. I am going to explain more details in the example.
EJS stands for embedded JavaScript. It lets us embed JavaScript code variables if statements loops inside of HTML.
How to render HTML from a EJS file?
Step One: Create a HTML page in EJS file
Firstly, in our server, we create a folder named “EJSDemo”. In this folder, we touch two files, one is “app.js”, and the other one is “home.ejs”.
We are going to write a simple HTML code in the “home.ejs” file.The instructor create a dog page, but I would like to create a “Fresh Food for Summer” page.
Step Two: Install EJS and Use res.render()
We need to type“npm install ejs –save”to install EJS first, so Express.js can connect and run the ejs file successfully.
Then, in the app.js file, we need to write“res.render(“XXX.ejs”)” inside the app.get function. This will allow the server to find the HTML page and send it back to user.
Step Three: Run the app
We open the default link on browser, and it shows the HTML page I just created.
However, this still have limitation for web application because it will only send back the exact same page every single time. In most web apps, that’s not what we want. In the next post, I will share my study notes to solve this problem.
网友评论