[英]How to import a http request (JSON format) from an API with Meteor
[英]How can I correctly format this JSON data from a backpack.tf API request?
我正在尝试使用我正在开发的 Discord Bot 的背包.tf API。 我目前正在尝试它的UserInfo部分。 在 API URL 中使用我自己的 Steam ID 会导致此 output
本质上,有users
,然后是 ID,最后是我尝试使用的实际信息。 我的代码如下:
const Discord = require("discord.js");
const superagent = require("superagent");
const { apiKey } = require("../db/config.json");
module.exports = {
run: async(client, message, args) => {
if (!args[0]) return message.channel.send("Enter in a steam ID!")
let id = args[0]
console.log(id)
let { body } = await superagent
.get(`https://backpack.tf/api/users/info/v1?steamids=${id}&key=${apiKey}`);
message.channel.send(
new Discord.MessageEmbed()
.setImage(body.users.id.avatar)
);
if (!{ body }) return message.channel.send("Check that ID again!");
},
aliases: ["bp"]
}
其中大部分只是框架,但它基本上是通过超级代理调用 API。 当它返回时,我尝试使用body.users.id.avatar
来获取用户的头像。 它不这样做,而是输出UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'avatar' of undefined
error。 API 在它只是body.users.id
时似乎没有给出任何错误,但是向它添加另一层会提示它中断。
我希望它只是给我我想要的结果。 谢谢。
看起来您正在尝试使用动态属性名称, body.users
是 object,其键值是带有数字的实际 id,不会有直接的.id
属性,因为body.users.id
是未定义的
body.users.id 没有给出任何错误的原因是因为它只是未定义,但您并没有尝试调用它的属性,就像您调用body.users.id.avatar
时所做的那样
body.users.id.avatar
=> undefined.avatar
这应该解决它:
body.users[id].avatar
这看起来如何的一个例子:
const id = "2324389";
const obj = {
"2324389": 23,
"1234678": 22,
"id": 21
};
obj.id
// => 21
obj[id]
// => 23
/* obj[id] is the same as below */
obj["2324389"]
// => 23
另外: if (!{ body })
这条线可能会给出错误,无论哪种方式,它都不会是错误的,因为它评估 object 是否真实,无论属性如何
如果您尝试对此进行错误处理,则它需要在代码中更早,并且您需要使用.catch
代替,除非 API 即使 ID 无效也不会引发错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.