嗨,我刚刚开始学习node.js 和javascript。我尝试使用 node-fetch 从 url 获取数据,然后尝试 json 解析数据,但我一直得到未定义的返回。
我试图从下面的html中的变量game中获取数据,然后进行字符串化,然后解析json,但它返回未定义。
我希望也许有人能帮我找出原因?
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");
async function serversFetch() {
try {
const servers = await fetch("https://get-servers.herokuapp.com/");
const data = await servers.text();
const servers_data = data.substring(
data.lastIndexOf("var game =") + 20,
data.lastIndexOf("game.init") - 10
);
return JSON.stringify(servers_data);
} catch (error) {
console.log(error);
}
}
(async () => {
const data = await serversFetch();
console.log('data', data);
const info = JSON.parse(data);
console.log('info', info.servers); // returns undefined
})()
如果我在没有servers
的情况下控制台日志info
,我会得到如下响应,但是当我尝试控制台日志info.servers
时,它会返回未定义。
info {
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
}
我使用 herokuapp 为任何想要提供帮助的人制作了一个示例网站。
最佳答案
我建议不要混合使用async/await
和.then
。这是一种使用 waits 来获取数据的方法。
const servers = await fetch("https://get-servers.herokuapp.com/");
const data = await servers.text();
// Work with data logic
关于javascript - Node.js从body中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63542620/