Hello Developers,
In this demonstration, I will try to discuss the URL
module in NodeJs. Every URL has its own parts. We will discuss this briefly. Let's look into the below URL
Let's dive into the URL
https://example.com/ -> This part is the host name
test.html -> This part is the path of the URL
?title=Hello&sub-title=World -> This part is the query of the URL
Now see all the things in the code
First, we need to create a server, that's why we need the HTTP
module. After that, we need to call the URL
module. A method named URL.Parse()
wiill be called and we have to pass the URL in the URL.parse()
. This method will turn the URL into an object.
By that object, we can get the hostname, path name, and query of the URL. The source code is given below:
var http = require('http');
var URL = require('url');
var server = http.createServer(function (request, response) {
var myURL = "https://example.com/test.html?title=Hello&sub-title=World";
var obj = URL.parse(myURL, true);
var myServerName = obj.host;
var myPathName = obj.path;
var mySearchQuery = obj.search;
response.writeHead(200, { 'Content-Type': 'text/html' });
response.write(myServerName);
// response.write(myPathName);
// response.write(mySearchQuery);
response.end();
})
server.listen(5000);
console.log('Server Running Successfully');
Just open the comment line to see the result. Then run the below command in the terminal:
node main.js
Hope this might help you in your journey of development.