How could I get my web App URL in Node.js? I mean if my site base url is http://localhost:8080/MyApp How could I get it?
Thanks,
To find the base URL of your website, go to the site's front page. What you see in the address bar on your site's front page is the base URL of your website.
To get the base URL in JavaScript, we use the window. location. origin and window. location.
The <base> tag specifies the base URL and/or target for all relative URLs in a document. The <base> tag must have either an href or a target attribute present, or both. There can only be one single <base> element in a document, and it must be inside the <head> element.
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.
To get the url like: http://localhost:8080/MyApp
we should use:-
req.protocol+"://"+req.headers.host
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With