discord.js中的节点获取无法读取属性

时间:2019-05-15 13:46:32

标签: node.js discord discord.js node-fetch

我一直在遵循Discord.js的REST API指南,但是我不断收到错误消息,指出无法读取返回json的第一个属性。我知道api地址正确。

响应如下所示: response

这是我的代码:

index.js

const Discord = require('discord.js');
const fetch = require('node-fetch');
const querystring = require('querystring');

const { prefix, token, api } = require('./config.json');

const client = new Discord.Client();

const trim = (str, max) => (str.length > max ? `${str.slice(0, max - 3)}...` : str);

client.once('ready', () => {
    console.log('Ready!');
});

client.on('message', async message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if (command === 'div2') {
        if (!args.length) {
            return message.channel.send('You need to supply a search term!');
        }

        const query = querystring.stringify({ name: args.join(' ') });

        const { body } = await fetch(`${api}search.php?${query}&platform=uplay`)
            .then(response => response.json());         

        if (!body.results.length) {
            return message.channel.send(`No results found for **${args.join(' ')}**.`);
        }

        const [answer] = body.results;

        const embed = new Discord.RichEmbed()
            .setColor('#EFFF00')
            .setTitle(answer.name)
            .addField('Platform', trim(answer.platform, 1024))
            .addField('Kills PvE', trim(answer.kills_npc, 1024));


        message.channel.send(embed);
    }
});

1 个答案:

答案 0 :(得分:0)

您的回复json图片没有body属性。因此,在进行destructuring assignment时,响应中没有对应的body可以分配给它。因此body是未定义的。

将解构方式更改为:

const { results } = await fetch(`${api}search.php?${query}&platform=uplay`)
  .then(response => response.json());
// results is array from the response

或者简单地说;不要破坏结构(您可以保留其余代码):

const body = await fetch(`${api}search.php?${query}&platform=uplay`)
  .then(response => response.json());