【问题标题】:Node.js and JSON: retreiving info from external website apiNode.js 和 JSON:从外部网站 api 检索信息
【发布时间】:2021-09-07 12:40:31
【问题描述】:

此代码不起作用,因为它无法读取外部网站的地址

需要该 json 文件中的“结果”值。

是否有一个简单的解决方法可以从外部网站读取 json?

更好的是,如果您愿意提供更多帮助,我希望它每 5 分钟重新扫描一次该网站(或者您可以设置任何时间)

谢谢!


    const fs = require("fs");
    fs.readFile("", "utf8", (err, jsonString) => {
      if (err) {
        console.log("Error reading json", err);
        return;
      }
      try {
        const useroutput = JSON.parse(jsonString);
        console.log("Customer address is:", useroutput.result); 
      } catch (err) {
        console.log("Error parsing JSON string:", err);
      }
    });
});


【问题讨论】:

  • 如果你不介意添加依赖,那么使用node-fetch?

标签: javascript node.js json discord discord.js


【解决方案1】:

HTTPS 模块是您正在寻找的,尽管有许多库可以使这些调用变得更容易。

const https = require('https');

const url = ''; // https://...
https.get(url, res => {
  // capture the response buffers
  const chunks = [];
  res.on('data', chunk => chunks.push(chunk));
  res.on('end', () => {
    const jsonString = Buffer.concat(chunks).toString('utf-8');
    // Handle as you will, JSON.parse(), etc.
  });
}).on('error', error => {
  console.log(error);
});

【讨论】:

    【解决方案2】:

    setInterval 是您所需要的。 @lucasvw提供的复制示例

    const https = require('https');
    const url = ''; // https://...
    setInterval(()=>{
    https.get(url, res => {
        // capture the response buffers
        const chunks = [];
        res.on('data', chunk => chunks.push(chunk));
        res.on('end', () => {
        const jsonString = Buffer.concat(chunks).toString('utf-8');
        // Handle as you will, JSON.parse(), etc.
        });
    }).on('error', error => {
        console.log(error);
    });
    },300000);
    

    【讨论】:

      猜你喜欢
      • 2018-01-03
      • 1970-01-01
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多