简体   繁体   中英

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,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM