Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get My Web App Base URL in JavaScript

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,

like image 717
Feras Odeh Avatar asked Apr 20 '12 18:04

Feras Odeh


People also ask

How do I find the URL URL of a base?

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.

What is base URL in JavaScript?

To get the base URL in JavaScript, we use the window. location. origin and window. location.

How do I find the base URL in HTML?

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.


3 Answers

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.

like image 114
pronevich Avatar answered Oct 11 '22 08:10

pronevich


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

we should use:-

req.protocol+"://"+req.headers.host
like image 35
Sandip Nag Avatar answered Oct 11 '22 08:10

Sandip Nag


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

like image 27
Md Razu Ahammed Molla Avatar answered Oct 11 '22 08:10

Md Razu Ahammed Molla