In this post, we will see how to create a web site in Node.js using express.
First of all, we open an editor (in my case Visual Studio Code), select the folder where we want to create our project and from the terminal we run the command npm init:
Then, we run the command npm to install express:
For this post, I don’t care about the warning.
If we open the file package.json, we will see the dependency between our project and Express:
[PACKAGE.JSON]
{
"name": "testwebsite",
"version": "1.0.0",
"description": "this a web site created using express",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Damiano",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}
Now, we create a folder in our project called pages, where we will put three html pages called:
[INDEX.HTML]
<!doctype html>
<html>
<head>
<title>Index</title>
<meta name="description" content="Index page">
</head>
<body>
<nav>
<a href="/">Index</a>
<a href="/about">About</a>
</nav>
<h1>Index Page</h1>
</body>
</html>
[ABOUT.HML]
<!doctype html>
<html>
<head>
<title>About</title>
<meta name="description" content="About page">
</head>
<body>
<nav>
<a href="/">Index</a>
<a href="/about">About</a>
</nav>
<h1>About Page</h1>
</body>
</html>
[404.HTML]
<!doctype html>
<html>
<head>
<title>404</title>
<meta name="description" content="404 page">
</head>
<body>
<nav>
<a href="/">Index</a>
</nav>
<h1>Page not found</h1>
</body>
</html>
Finally, we create the file index.js where will put the functionalities of the site web:
[INDEX.JS]
const { response, request } = require('express');
const express = require('express');
// creation of an instance of express
const application = express();
// listen for request on port 8000
application.listen(8000)
// definition of page requests
// index
application.get('/', (request, response) =>{
response.sendFile('./pages/index.html', {root: __dirname});
});
// about
application.get('/about', (request, response) =>{
response.sendFile('./pages/about.html', {root: __dirname});
});
// definition of a redirect for index
application.get('/index', (request, response) =>{
response.redirect('/');
});
// definition of the 404 page
application.use((request, response) =>{
response.status(404).sendFile('./pages/404.html', {root: __dirname});
});
Now, if we run the application (with the command node index.js) this will be the result: