【问题标题】:How to get full URL in Node.js?如何在 Node.js 中获取完整的 URL?
【发布时间】:2019-04-08 15:59:29
【问题描述】:

我有一个网址https://twitter.com/Javeria85685955/status/1059335612346650624 我想在运行时在 Node.js 中获取完整的 url。我正在使用puppeteer 抓取。

我的代码是

const url = require('url');
const myURL = url.parse(req.url, true);
console.log('This is a full URL: ' + JSON.stringify(myURL))

它给了我这样的输出

这是一个完整的网址:

{
    "protocol": null,
    "slashes": null,
    "auth": null,
    "host": null,
    "port": null,
    "hostname": null,
    "hash": null,
    "search": null,
    "query": {},
    "pathname": "/",
    "path": "/",
    "href": "/"
}

但我需要所需的输出

https://twitter.com/Javeria85685955/status/1059335612346650624

【问题讨论】:

  • 什么是req.url?输出表明它是空白的。我不知道您如何期望计算机能够从“无”变为 twitter.com 上的 URL。
  • 你是推特开发者吗?
  • 来自回调函数
  • 我是 nodejs 开发者。
  • 我想在运行时获取 url。我正在使用 puppeteer nodejs 模块。

标签: javascript node.js url puppeteer


【解决方案1】:

如果您使用的是puppeteer,那么为什么不利用puppeteer API 来检索您的网址,如下所示:

const url = await page.url();
console.log(url); // This will output the current URL to the console

对我来说似乎是最简单的解决方案?

【讨论】:

  • 这个游戏只有基本网址。在示例“example.com”中,而不是 example.com/thisismy.html。 @AJC24
【解决方案2】:

试试这个:

const myURL = req.headers.referer;

【讨论】:

  • 返回和之前一样的结果
  • 尝试从 req.headers.host 获取主机名和从 req.url 获取 URL
猜你喜欢
  • 2012-04-28
  • 2015-03-11
  • 2016-07-05
  • 1970-01-01
  • 2013-06-08
  • 2017-06-06
  • 2015-10-28
  • 2012-02-07
相关资源
最近更新 更多