提问者:小点点

节点js从主体提取数据


嗨,我今天刚刚开始学习Node.js和javascript。我试图从一个url获取数据,然后尝试用json解析数据,但我一直得到一个错误。

错误:

(node:25889) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token v in JSON at position 0

我正试图从下面的html中获取可变游戏的数据,希望有人能帮我弄清楚为什么我不能让它工作?

html代码不是我的,我试图从一个我不控制的站点获取数据。

页面HTML:

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8" />
    <title>Document Title</title>
  </head>
  <body>
    <div id="hud-div">
      <p>Welcome to the blah blah blah blah text here</p>
    </div>
    <script>
      var game = new Game({
        stage: "prod",
        servers: {
          v32306117: {
            id: "v32306117",
            region: "region 1",
            name: "region #1",
            hostname: "hostname1",
            port: 80,
            fallbackPort: 8000,
            population: 97,
            selected: false
          },
          v32306125: {
            id: "v32306125",
            region: "region 2",
            name: "region #2",
            hostname: "hostname2",
            port: 80,
            fallbackPort: 8000,
            population: 38,
            selected: false
          }
        },
        userGroup: 0
      });

      game.init(function() {
        game.assetManager.load([{
          "name": "\/asset\/image\/map\/grass.png",
          "url": "\/asset\/image\/map\/grass.png"
        }]);

        game.debug.init();
        game.run();
      });

    </script>
  </body>
</html>

提取函数:

const fetch = require("node-fetch");
let servers;

async function getServers() {
  try {
    fetch("https://SiteUrl.com").then(data =>
        data.text().then(text =>
            text.substring(
              text.lastIndexOf("var game ="),
              text.lastIndexOf("game.init") - 10
            ))
      ).then(res => servers = JSON.parse(res));
    
  } catch (error) {
    console.error(error);
  }
}

getServers();

对不起,我的英语不是很好


共1个答案

匿名用户

您在代码中出现语法错误

const fetch = require("node-fetch");
let servers;

async function getServers() {
  try {
    fetch("https://quote-garden.herokuapp.com/api/v2/quotes/random").then(data => {
        console.log(data)
        }
      ).then(res => servers = JSON.parse(res));
  } catch (error) {
    console.error(error);
  }
}

(async () => {
  const data = await getServers();
  console.log(data);
})()

这里我做了一些改动

first The后面缺少{}方括号