Hello Developers,
In this tutorial, I will show you how to deal with requests and responses. First of all, we need to understand what is a request and what is the response. Request and response both are parameters of call back function. When the user wants something from the server, it is called a request. The response is the reply of the server sent to the browse.
For creating any server, we need to use the createServer()
method the code is given below:
createServer() Method
const http = require('http');
const server = http.createServer((request, response) => {
// magic happens here!
});
A callback function is called in the createServer()
method.
req.url == "/"
To get any URL
, which means if we request anything, after the backslash, we need to write the below code:
var server = http.createServer(function (req, res) {
if (req.url == "/") {
res.writeHead('200', { 'Content-Type': 'Text/html' })
res.write('<h3>This is Home Page</h3>')
res.end();
} else if (req.url == "/about") {
res.writeHead('200', { 'Content-Type': 'Text/html' })
res.write('<h3>This is About Page</h3>')
res.end();
} else if (req.url == "/contact") {
res.writeHead('200', { 'Content-Type': 'Text/html' })
res.write('<h3>This is Contact Page</h3>')
res.end();
}
});
server.listen()
By the command server.listen()
, we specify the port number. The complete code is given below:
var http = require('http');
var server = http.createServer(function (req, res) {
if (req.url == "/") {
res.writeHead('200', { 'Content-Type': 'Text/html' })
res.write('<h3>This is Home Page</h3>')
res.end();
} else if (req.url == "/about") {
res.writeHead('200', { 'Content-Type': 'Text/html' })
res.write('<h3>This is About Page</h3>')
res.end();
} else if (req.url == "/contact") {
res.writeHead('200', { 'Content-Type': 'Text/html' })
res.write('<h3>This is Contact Page</h3>')
res.end();
}
});
server.listen(5000);
console.log('Server running Successfully');
I hope this might help you in the journey of development.
Read More: How to run Hello World in Node Server