Node.js uses JavaScript to build entire server side application. This means it can be used to build different types of applications such as command line application, web application, real-time chat application, REST API server etc. However, it is mainly used to build network programs like web servers, similar to PHP, Java, or ASP.NET.
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 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 a very basic web server to handle http requests
const http = require("http");
http.createServer((req, res) => {
try {
// res.writeHead(200, {'Content-Type': 'text/html'});
res.statusCode = 200;
res.write("hello");
res.end();
} catch (error) {
console.log("here");
}
}).listen(3500);
To run the above program open the command line and type node server.js
Explaination
- We import the built-in http module.
- create a http server, with a request-response cycle
- tell the server to listen on port 3500
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 request body. The response object can be used to send a response for a current HTTP request.
Request-Response Cycle
var http = require('http');
var server = http.createServer(function (req, res) {
if (req.url == '/') { //check the URL of the current request
res.writeHead(200, { 'Content-Type': 'application/json' });
res.write('<html><body><p>This is home Page.</p></body></html>');
res.end();
}
else if (req.url == "/admin") {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is admin Page.</p></body></html>');
res.end();
}
else
res.end('Invalid Request!');
}
});
server.listen(5000);
Thank you, Please follow me
Top comments (0)