20

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

谢谢,

4

3 回答 3

37

您必须连接“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);

升级版:

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

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

于 2012-04-20T20:46:04.803 回答
12

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

我们应该使用:-

req.protocol+"://"+req.headers.host
于 2019-01-21T12:29:23.057 回答
2

用于在您的节点应用程序中获取 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

于 2017-07-26T10:17:01.323 回答