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
Step.1: Import Node.js core module
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.
Handle HTTP Request:
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.
Sending JSON Response