Chapter 4
Chapter 4
Introduction: To access web pages of any web application, you need a web server. The web server will
handle all the http requests for the web application e.g IIS is a web server for ASP.NET web applications
and Apache is a web server for PHP or Java web applications.
Node.js provides capabilities to create your own web server which will handle HTTP requests
asynchronously. You can use IIS or Apache to run Node.js web application 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.
});
In the above example, 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. The next step is to call createServer() method of http and
specify callback function with request and response parameter. Finally, call listen() method of server object
which was returned from createServer() method with port number, to start listening to incoming requests on
port 5000. You can specify any unused port here.
Run the above web server by writing node server.js command in command prompt or terminal window and
it will display message as shown below.
This is how you create a Node.js web server using simple steps. Now, let's see how to handle HTTP request
and send response in Node.js web server.
}
else if (req.url == "/student") {
}
else if (req.url == "/admin") {
}
else
res.end('Invalid Request!');
});
To test it, you can use the command-line program curl, which most Mac and Linux machines have
pre-installed.
curl -i http://localhost:5000
HTTP/1.1 200 OK
Content-Type: text/plain
Date: Tue, 8 Sep 2015 03:05:08 GMT
Connection: keep-alive
This is home page.
For Windows users, point your browser to http://localhost:5000 and see the following result.
The same way, point your browser to http://localhost:5000/student and see the following result.
It will display "Invalid Request" for all requests other than the above URLs.