28

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,

Feras Odeh
  • 9,136
  • 20
  • 77
  • 121

3 Answers3

40

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.

pronevich
  • 856
  • 8
  • 12
17

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

we should use:-

req.protocol+"://"+req.headers.host
Sandip Nag
  • 968
  • 2
  • 18
  • 34
2

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