1 Environment
1
2
3
4
|
$ node -v
v14.17.0
$ npm -v
6.14.13
|
1 Install express.js
1
|
$ npm install express --save
|
2 Simple application
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
const port = 3000,
express = require("express"),
app = express();
app
.get("/", (req, res) => {
res.send("Hi Express!") // send response to client
console.log(req.params);
console.log(req.body);
console.log(req.url);
console.log(req.query);
})
.listen(port, () => {
console.log(`The Express.js sever has started and is listening port:` + `${port}`);
});
|
Start server:
1
2
|
$ node main
The Express.js sever has started and is listening port:3000
|
Then you can access http://localhost:3000/
to via browser.
Comparing to node.js simple web server, many step is hidden under the library.
3 Application using express-ejs-layouts
3.1 Install packages
ejs
and express-ejs-layouts
support express and ejs web page template.
1
|
$ npm i ejs express express-ejs-layouts http-status-codes -S
|
3.2 Use ejs template
source
Code structure
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
├── main.js
├── controllers
│ ├── errorController.js
│ └── homeController.js
├── package-lock.json
├── package.json
├── public
│ ├── 404.html
│ └── 405.html
└── views
├── index.ejs
├── layout.ejs
└── partials
└── navigation.ejs
|
For using ejs template, main.js
calls:
1
2
|
const layouts = require("express-ejs-layouts");
app.user(layouts);
|
views/layout.ejs
defines the template, like:
1
2
3
4
5
6
7
8
|
<body>
<%- include('partials/navigation') %>
<div>
<%- body %>
</div>
<div id="footer" class="block">FOOTER</div>
</body>
</html>
|
Then the other pages like views/index.ejs
supplement the <%- body %>
parts at layout.ejs
like:
index.ejs
1
2
|
<% let name = "Hoge"; %>
<h1>Hello, <%= name %></h1>
|
3.3 Run server
As I installed nodemon
by npm i nodemon -S
and add below to package.json
,
1
2
3
|
"scripts": {
"start": "nodemon start"
},`
|
Start server by:
1
2
3
|
$ npm start
...
Server running at http://localhost:3000
|
Then web page is generated by template.
Reference