node -fetch в discord.js не может прочитать свойство

Я следил за руководством по REST API из Discord.js, но все время получаю ошибки, что первое свойство возвращаемого 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);
    }
});

person Zoef    schedule 15.05.2019    source источник
comment
А в чем проблема с кодом?   -  person alex55132    schedule 15.05.2019


Ответы (1)


В вашем ответе 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());
person 1565986223    schedule 15.05.2019