以其他方式在 Node JS 中获取特定的 URL

Get a particular URL in Node JS other ways

我有 Reddit 的 REST API。我正在尝试解析 JSON 输出以获得响应的 URL。当我尝试发送请求时,我得到了多个输出,但我不确定该怎么做,因为它是随机响应。

https
  .get("https://www.reddit.com/r/cute/random.json", resp => {
    let data = "";

    resp.on("data", chunk => {
      data += chunk;
    });

    const obj = JSON.parse(data);
    resp.on("end", () => {
      console.log(obj.url);
    });
  })
  .on("error", err => {
    console.log("Error: " + err.message);
  });

这是我得到的代码。我使用了默认的 Node 的 http 库,但我认为它不起作用。我从来没有使用过任何节点库,所以如果你也能推荐它们会很有帮助。也让我知道我做的是否正确。

我知道 http 是 Node JS 的核心库,但我强烈建议您使用 node-fetch 之类的东西。确保 运行 在 package.json 文件所在的终端(或 cmd)上执行以下命令:

$ npm install node-fetch

这将安装 node-fetch 库,其作用类似于基于 Web 的 fetch 工作方式。

const fetch = require("node-fetch");
const main = async () => {
  const json = await fetch("https://www.reddit.com/r/cute/random.json").then(
    res => res.json()
  );
  console.log(
    json
      .map(entry => entry.data.children.map(child => child.data.url))
      .flat()
      .filter(Boolean)
  );
};
main();

您要找的 URL,我可以在 data.children[0].data.url 中找到,所以我在那里做了一张地图。希望这对您有所帮助。

我得到了相同代码的多个输出,运行 多次,因为您使用的 URL 是随机文章获取 URL。来自他们的 wiki:

/r/random takes you to a random subreddit. You can find a link to /r/random in the header above. Reddit gold members have access to /r/myrandom, which is right next to the random button. Myrandom takes you to any of your subscribed subreddits randomly. /r/randnsfw takes you to a random NSFW (over 18) subreddit.

我的输出是这样的:

[ 'https://i.redd.it/pjom447yp8271.jpg' ]   // First run
[ 'https://i.redd.it/h9b00p6y4g271.jpg' ]   // Second run
[ 'https://v.redd.it/lcejh8z6zp271' ]       // Third run

因为只有一个URL,我改了代码得到第一个:

const fetch = require("node-fetch");
const main = async () => {
  const json = await fetch("https://www.reddit.com/r/cute/random.json").then(
    res => res.json()
  );
  console.log(
    json
      .map(entry => entry.data.children.map(child => child.data.url))
      .flat()
      .filter(Boolean)[0]
  );
};
main();

现在它给了我:

'https://i.redd.it/pjom447yp8271.jpg'   // First run
'https://i.redd.it/h9b00p6y4g271.jpg'   // Second run
'https://v.redd.it/lcejh8z6zp271'       // Third run
'https://i.redd.it/b46rf6zben171.jpg'   // Fourth run

预览

希望对您有所帮助。如果您需要更多帮助,请随时问我。其他替代方案包括 axios,但我不确定这是否可以在后端使用。