We need the web server to access web pages of any web application. The web server will handle all the http requests for the web application.
IIS is a web server for ASP.NET web applications and Apache is a web server for PHP or Java web applications.
Node.js has capabilities to create own web server which will handle HTTP requests asynchronously. We can use IIS or Apache to run Node.js web application as well but it is recommended to use Node.js web server.
Create Node.js Web Server
Node.js makes it easy to create a simple web server that processes incoming requests asynchronously.
NodeServer.js
<!-- Step. 1: Import Node.js core module -->
varhttp = require(
'http');
varserver = http.createServer(
function(req, res) {
<!-- Step. 2: Handles incoming requests here -->
});
<!-- Step. 3: Listen for any incoming requests -->
server.listen(8080);
console.log(
'Node.js web server is running on port 8080..');
Step.1: Import Node.js core module
We import the http module using require() function. The http module is a core module of Node.js, so no need to install it using NPM.
Step.2: Handles incoming requests here
The next step is to call createServer() method of http and specify callback function with request and response parameter.
Step.3: Listen for any incoming requests
Finally, call listen() method of server object which was returned from createServer() method with port number, to start listening to incoming requests on port 8080. We can specify any unused port here.
Output:
D:\node>node NodeServer.js
Node.js web server is running on port 8080..
Handle HTTP Request:
The http.createServer() method includes request and response parameters which is supplied by Node.js. The request object can be used to get information about the current HTTP request e.g. URL, request header and the data. The response object can be used to send a response for a current HTTP request.
HandleHttpReqRes.js
<!-- Import Node.js core module -->
var http = require('http');
<!-- create web server -->
var server = http.createServer(function (req, res) {
<!-- Check the URL of the current request -->
if (req.url == '/') {
// set response header
res.writeHead(200, { 'Content-Type': 'text/html' });
// set response content
res.write('<html><body><p>Home Page</p></body></html>');
console.log('http://localhost:8080: Home Page..')
res.end();
} else if (req.url == "/admin") {
res.writeHead(200, { 'Content-Type': 'text/html' });
console.log('http://localhost:8080/admin: Admin Page..')
res.write('<html><body><p>Admin Page</p></body></html>');
res.end();
} else {
res.end('Invalid Request!');
}
});
<!-- listen for any incoming requests -->
server.listen(8080);
console.log('Node.js web server at port 8080 is running..');
In the above example, req.url is used to check the URL of the current request and based on that it sends the processed response. To send a response, first it sets the response header using writeHead() method and then writes a string as a response body using write() method.
Finally, Node.js web server sends the response using end() method.
D:\node>node HandleHttpReqRes.js
Node.js web server at port 8080 is running..
http://localhost:8080: Home Page..
http://localhost:8080/admin: Admin Page..
Sending JSON Response
The following example demonstrates how to serve JSON response from the Node.js web server.
HttpJSONRes.js
varhttp = require(
'http');
varserver = http.createServer(
function(request, response) {
<!-- Check whether the URL is currect or not. -->
if
(request.url ==
'/data') {
response.writeHead(200, {
'Content-Type':
'application/json'});
response.write(JSON.stringify({ message:
"Hello World"}));
response.end();
}
});
server.listen(8080);
console.log(
'Node.js web server at port 8080 is running..');
Output
D:\node>node HttpJSONRes.js
Node.js web server at port 8080 is running..
{"message":"Hello World"}