简体   繁体   English

使用JavaScript获取我的Web App基本URL

[英]Get My Web App Base URL in JavaScript

How could I get my web App URL in Node.js? 我如何在Node.js中获取我的Web应用程序URL? I mean if my site base url is http://localhost:8080/MyApp How could I get it? 我的意思是如果我的站点基本URL是http:// localhost:8080 / MyApp我怎么能得到它?

Thanks, 谢谢,

You must connect 'url' module 您必须连接'url'模块

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: UPD:

In Node.js v8 url module get new API for working with URLs. 在Node.js v8 url模块中获取用于处理URL的新API。 See documentation : 文档

Note: While the Legacy API has not been deprecated, it is maintained solely for backwards compatibility with existing applications. 注意:虽然旧版API尚未弃用,但它仅用于向后兼容现有应用程序。 New application code should use the WHATWG API. 新的应用程序代码应该使用WHATWG API。

To get the url like: http://localhost:8080/MyApp 获取URL如: http:// localhost:8080 / MyApp

we should use:- 我们应该使用: -

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

For getting url details in your node apps. 用于获取节点应用程序中的URL详细信息。 You have to use URL module. 您必须使用URL模块。 URL module will split your web address into readable parts URL模块会将您的网址拆分为可读部分

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 要了解有关URL模块的更多信息,请访问https://nodejs.org/api/url.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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