Let's Start our First Express Server
I made a small basic server with Node.js, and Express.js enhances the best way to manage and create server or APIs, but right now we are going to see
Let's Implement a simple web server using Express framework , Implement a web server that serves static content
What is Express.js?
Express.js is a Web Framework mainly using for Back End that have many characteristics like minimal, fast, flexible, etc.
Minimal: because less is more, means it has the enough characteristics to completely fulfill your server-side application without any problem, or you can add all you need or replace the unnecessary packages, giving us the fresh air that we need.
Flexible: Express accepts HTTP request and return with HTTP response
Fast: The Express.js team focus on the performance to manage high traffic websites and many companies are using it
A Simple Server using Express:
- Create a folder named node-express in the NodeJS folder and move to that folder.
- create a subfolder named public.
- the public folder, create a file named index.html and add the following code to it:
<html>
<title>This is index.html</title>
<body>
<h1>Index.html</h1>
<p>This is the contents of this file</p>
</body>
</html>
- Similarly create an aboutus.html file and add the following code to it:
<html>
<title>This is aboutus.html</title>
<body>
<h1>Aboutus.html</h1>
<p>This is the contents of the aboutus.html file</p>
</body>
</html>
- At the prompt, type the following to initialize a package.json file in the node-express folder:
npm init
Accept the standard defaults suggested until you end up with a package.json file containing the following:
{
"name": "node-express",
"version": "1.0.0",
"description": "Node Express Examples",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index"
},
"author": "Jogesh Muppala",
"license": "ISC"
}
- Then, install the Express framework in the folder by typing the following at the prompt:
npm install express@4.16.3 --save
- Create a file named index.js and add the following code to it:
const express = require('express'),
http = require('http');
const hostname = 'localhost';
const port = 3000;
const app = express();
app.use((req, res, next) => {
console.log(req.headers);
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end('<html><body><h1>This is an Express Server</h1></body></html>');
});
const server = http.createServer(app);
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
- Start the server by typing the following at the prompt, and then interact with the server:
npm start
Serving Static Files
- Install morgan by typing the following at the prompt. Morgan is used for logging purposes:
npm install morgan@1.9.0 --save
- Update index.js as follows:
. . .
const morgan = require('morgan');
. . .
app.use(morgan('dev'));
app.use(express.static(__dirname + '/public'));
. . .