Get My Web App Base URL in JavaScript


Question

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,

1
8
4/20/2012 8:00:14 PM

Accepted Answer

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.

27
6/1/2017 4:01:14 PM

To get the url like: http://localhost:8080/MyApp

we should use:-

req.protocol+"://"+req.headers.host

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon