Get My Web App Base URL in JavaScript
You must connect 'url' module
var http = require('http');
var url = require('url') ;
http.createServer(function (req, res) {
var hostname = req.headers.host; // hostname = 'localhost:8080'
var pathname = url.parse(req.url).pathname; // pathname = '/MyApp'
console.log('http://' + hostname + pathname);
res.writeHead(200);
res.end();
}).listen(8080);
UPD:
In Node.js v8 url module get new API for working with URLs. See documentation:
Note: While the Legacy API has not been deprecated, it is maintained solely for backwards compatibility with existing applications. New application code should use the WHATWG API.
For getting url details in your node apps. You have to use URL module. URL module will split your web address into readable parts
Following I have given the code
var url = require('url');
var adr = 'http://localhost:8080/default.htm?year=2017&month=february';
var q = url.parse(adr, true);
console.log(q.host); //returns 'localhost:8080'
console.log(q.pathname); //returns '/default.htm'
console.log(q.search); //returns '?year=2017&month=february'
var qdata = q.query; //returns an object: { year: 2017, month: 'february' }
console.log(qdata.month); //returns 'february'`enter code here`
To learn more about URL module you can visit https://nodejs.org/api/url.html
To get the url like: http://localhost:8080/MyApp
we should use:-
req.protocol+"://"+req.headers.host