在JavaScript中获取我的Web应用程序的基本URL

我怎么能在Node.js中获得我的Web应用程序URL? 我的意思是如果我的网站基地的URL是http:// localhost:8080 / MyApp我怎么能得到它?

谢谢,

你必须连接'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:

在Node.js v8 url模块中获取用于处理URL的新API。 请参阅文档 :

注意:虽然旧版API尚未被弃用,但它仅用于与现有应用程序的后向兼容性。 新的应用程序代码应该使用WHATWG API。

获取节点应用程序中的url详细信息。 你必须使用URL模块。 URL模块将您的url分成可读部分

我已经给了代码

 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` 

要了解有关URL模块的更多信息,请访问https://nodejs.org/api/url.html