#
Read a URL Request in Node.js
This tutorial explains how we can read and parse the URL received by Node.js in a request.
The URL module in Node.js splits up (parse) a web address into readable parts, and you can do a lot of interesting things after that. You can redirect the request or create the response based of the page parameters you receive. The last case is explained bellow.
Using the URL module will not let you read the URL you receive from the request. This module let you parse a URL string.
If you want to read the URL you receive from a request in Node.js, you have to use the HTTP module in Node.js.
In order to use the URL module in Node.js you have to import the module into the application using the require()
method.
Here it is an example of using URL module in Node.js:
var http = require('http');
var urlAddr = require('url');
console.log('START Node.js application ...');
http.createServer(function (req, res) {
var var1 = urlAddr.parse(req.url, true);
var shortUrl = var1.pathname;
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The relative URL you enterd is: "+shortUrl);
return res.end();
}).listen(8082);
... and here it is the execution on the console:
When you type a request in the browser, you will get the following result: