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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10251805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:29:28  来源:igfitidea点击:

Get My Web App Base URL in JavaScript

javascriptnode.js

提问by Feras Odeh

How could I get my web App URL in Node.js? I mean if my site base url is http://localhost:8080/MyAppHow could I get it?

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

Thanks,

谢谢,

回答by pronevich

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:

更新:

In Node.js v8 url module get new API for working with URLs. See documentation:

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

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.

注意:虽然 Legacy API 没有被弃用,但它的维护只是为了与现有应用程序向后兼容。新的应用程序代码应该使用 WHATWG API。

回答by Sandip Nag

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

获取如下网址:http://localhost:8080/MyApp

we should use:-

我们应该使用:-

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

回答by Md Razu Ahammed Molla

For getting url details in your node apps. You have to use URL module. URL module will split your web address into readable parts

用于在您的节点应用程序中获取 url 详细信息。您必须使用 URL 模块。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