The Node.js HTTP module allows us to create web servers and handle HTTP requests and responses. It is a built-in module, so we do not need to install an external package to use it.
HTTP stands for Hypertext Transfer Protocol. It is used for communication between a client, such as a browser, and a server.
Browser
|
| HTTP Request
v
Node.js HTTP Server
|
| HTTP Response
v
Browser Displays Result
Node.js provides the HTTP module by default. We can import it
using the require() function in CommonJS.
const http = require('http');
console.log('HTTP module loaded successfully.');
HTTP module loaded successfully.
The http variable now provides methods for
creating HTTP servers and making HTTP requests.
We can create a server using the
http.createServer() method.
const http = require('http');
const server = http.createServer(function (req, res) {
res.end('Hello World from Node.js!');
});
server.listen(3000, function () {
console.log('Server running at http://localhost:3000');
});
Server running at http://localhost:3000
Hello World from Node.js!
server.js, run node server.js,
and open
http://localhost:3000 in your browser.
Keep the terminal running while testing.
The callback passed to createServer() receives two
important objects: req and res.
| Object | Full Name | Purpose |
|---|---|---|
req |
Request | Contains information about the incoming request. |
res |
Response | Used to send a response to the client. |
const http = require('http');
const server = http.createServer(function (req, res) {
res.setHeader('Content-Type', 'text/plain');
res.end(
'Method: ' + req.method +
'\nURL: ' + req.url
);
});
server.listen(3000, function () {
console.log('Server started on port 3000');
});
Open http://localhost:3000/about.
Method: GET
URL: /about
req.method gives the HTTP method, while
req.url gives the requested path and query
string.
We can send HTML content from the server by setting the response
content type to text/html.
const http = require('http');
const server = http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'
});
res.end(`
<!DOCTYPE html>
<html>
<head>
<title>My Node.js Website</title>
</head>
<body>
<h1>Welcome to Soopro Pathshala</h1>
<p>This page is served by Node.js.</p>
</body>
</html>
`);
});
server.listen(3000, function () {
console.log('Open http://localhost:3000');
});
This page is served by Node.js.
An HTTP status code tells the client whether a request was successful or whether something went wrong.
| Status Code | Meaning |
|---|---|
200 |
OK — the request succeeded. |
201 |
Created — a resource was created. |
400 |
Bad Request — the request is invalid. |
401 |
Unauthorized — authentication is required or invalid. |
404 |
Not Found — the requested resource was not found. |
500 |
Internal Server Error — the server encountered an error. |
const http = require('http');
const server = http.createServer(function (req, res) {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Request successful!');
});
server.listen(3000);
The statusCode property sets the response
status code. The example sends 200 OK.
We can check req.url to return different responses
for different paths. This is a simple way to understand routing
before learning Express.js.
const http = require('http');
const server = http.createServer(function (req, res) {
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
if (req.url === '/') {
res.statusCode = 200;
res.end('Welcome to the Home Page');
} else if (req.url === '/about') {
res.statusCode = 200;
res.end('This is the About Page');
} else if (req.url === '/contact') {
res.statusCode = 200;
res.end('This is the Contact Page');
} else {
res.statusCode = 404;
res.end('404 - Page Not Found');
}
});
server.listen(3000, function () {
console.log('Server running on port 3000');
});
http://localhost:3000/http://localhost:3000/abouthttp://localhost:3000/contacthttp://localhost:3000/xyz
The write() method sends part of a response.
The end() method finishes the response. You can
call end() without write() when you
want to send a single response body.
const http = require('http');
const server = http.createServer(function (req, res) {
res.setHeader('Content-Type', 'text/plain');
res.write('Hello ');
res.write('Students!');
res.end();
});
server.listen(3000);
Hello Students!
end() when the response is complete.
Do not try to write additional data after ending the response.
| Method or Property | Purpose |
|---|---|
http.createServer() |
Creates an HTTP server. |
server.listen() |
Starts listening on a port or address. |
req.method |
Provides the incoming HTTP method, such as GET or POST. |
req.url |
Provides the request path and query string. |
res.statusCode |
Sets or reads the response status code. |
res.setHeader() |
Sets a response header. |
res.write() |
Writes a response body chunk. |
res.end() |
Completes the response. |
3000./about route./courses route that displays your course names.404 for unknown routes.Challenge: Display the request method and URL on a separate route.
Select the correct answer for each question.
1. Which method creates an HTTP server?
2. Which object is used to send a response to the client?
3. Which status code means that a page was not found?