[英]need help to use an api response in my code
To start off I am a noob at this coding game.首先,我是这个编码游戏的菜鸟。 started a couple of days ago.
几天前开始。 i am making a chatbot for twitch to use in my channel for fun.
我正在制作一个用于 twitch 的聊天机器人,以便在我的频道中使用以获取乐趣。 got the bot up and going and started to make commands.
让机器人启动并开始发出命令。 I am hoping to create an uptime command and have managed to get as far as requesting the data from the helix API but I am now completely stumped on how to "use" it.
我希望创建一个正常运行时间命令,并设法从 helix API 请求数据,但我现在完全不知道如何“使用”它。
const querystring = require("querystring"),
fetch = require("node-fetch");
const CLIENT_ID = "###";
const STREAMS_URL = "https://api.twitch.tv/helix/streams/";
var started_at = ""
const qs = querystring.stringify({
user_login: "lil__gizmo"
});
const qUrl = `${STREAMS_URL}?${qs}`;
const fetchArgs = {
headers: {
"Client-ID": CLIENT_ID,
'Authorization': 'Bearer ' + "###"
}
};
fetch(qUrl, fetchArgs)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
the response I get is我得到的回应是
{
data: [
{
id: '38236753072',
user_id: '63931875',
user_name: 'Lil__Gizmo',
game_id: '497057',
type: 'live',
title: 'FEAR THE REAPERS!!!',
viewer_count: 6,
started_at: '2020-05-23T13:09:18Z',
language: 'en',
thumbnail_url: 'https://static-cdn.jtvnw.net/previews-ttv/live_user_lil__gizmo-{width}x{height}.jpg',
tag_ids: [Array]
}
],
pagination: {}
}
I am trying to take the started_at
property of the returned object and use it in my code.我正在尝试获取返回的 object 的
started_at
属性并在我的代码中使用它。
In your code:在您的代码中:
fetch(qUrl, fetchArgs)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
You can do:你可以做:
fetch(qUrl, fetchArgs)
.then(res => res.json())
.then(data => {
const { started_at } = data.data[0];
})
.catch(err => console.error(err));
You can then do what you like with that variable.然后,您可以使用该变量做您喜欢的事情。
You can use async-await
syntax您可以使用
async-await
语法
You making async operation so you have to do this operation in function.您进行异步操作,因此您必须在 function 中执行此操作。
let data;
async function getData() {
try {
data = await fetch(qUrl, fetchArgs).then(res => res.json());
} catch (error) {
console.log(error);
}
}
getData();
//Wait for 2 minutes to get data from server
setTimeout(() => {
console.log(data.data[0].started_at);
}, 2000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.