You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用nekos.life API获取猫图时遇TypeError问题求助

解决snekfetch请求API时response为null的问题

你遇到的TypeError: Cannot read property 'body' of null错误,本质是请求https://nekos.life/api/v2/img/meow时失败了,导致回调里的response为null,此时直接访问response.body就会抛出异常。

修复步骤

  1. 添加错误处理逻辑:在snekfetch的.end()回调中,先判断err是否存在,这是请求失败的直接标识。
  2. 校验响应有效性:即使没有err,也要检查response和response.body是否存在,避免因响应格式异常导致报错。

修改后的代码

const superagent = require("snekfetch");
const Discord = require('discord.js')

module.exports = {
  name: "cat",
  category: "fun",
  description: "Sends a random image of a cat",
  usage: "[command]",
  run: async (client, message, args, level) => {
    superagent.get('https://nekos.life/api/v2/img/meow')
      .end((err, response) => {
        // 处理请求错误
        if (err) {
          return message.channel.send(`获取猫咪图片失败:${err.message}`);
        }
        // 校验响应数据完整性
        if (!response || !response.body || !response.body.url) {
          return message.channel.send('无法获取有效的猫咪图片链接');
        }
        const lewdembed = new Discord.MessageEmbed()
          .setTitle("Random cat")
          .setImage(response.body.url)
          .setColor(`#00FF00`)
          .setFooter(`owo`)
          .setURL(response.body.url);
        message.channel.send(lewdembed);
      })
  }
};

额外建议

snekfetch已经停止维护,后续可以考虑替换为node-fetch或axios这类活跃维护的HTTP请求库,它们的错误处理和API设计更直观。

内容的提问来源于stack exchange,提问作者Daniel Weatherall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 17:20:59