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

调用Reddit随机帖子接口时遇SyntaxError: Unexpected token u错误

解决Reddit API请求时JSON.parse触发SyntaxError: Unexpected token u的问题

问题说明

调用Reddit随机帖子接口后,执行JSON.parse(data.body)触发如下错误:

SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at Object.run (file:///C:/x/v44bot/src/commands/reddit.js:13:24)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

同时数据返回undefined,无法正常获取帖子内容。

错误原因

  1. 重复解析JSON:response.json()方法已经自动将HTTP响应体解析为JSON对象,无需再调用JSON.parse()。
  2. 不存在的属性:解析后的data对象没有body属性,data.body返回undefined,传给JSON.parse()时会被转为字符串"undefined",解析时自然触发语法错误。
  3. 未定义的channel变量:代码中直接使用channel.send(),但channel未被声明或赋值,在Discord.js的slash命令中应使用interaction对象的相关方法。

修复后的代码

import { EmbedBuilder, SlashCommandBuilder } from "discord.js";
import fetch from "node-fetch";

export default {
    data: new SlashCommandBuilder()
      .setName("hoodclassic")
      .setDescription("haha so funny"),
    run: async (client, interaction) => {
        // 提前回复防止超时(slash命令要求3秒内响应)
        await interaction.deferReply();
        
        const embed = new EmbedBuilder();
        try {
            // 添加User-Agent头,Reddit API要求
            const response = await fetch('https://reddit.com/r/hoodironycentral/random/.json', {
                headers: {
                    'User-Agent': 'Discord Bot v1.0 (your-bot-info)'
                }
            });
            
            // response.json()已直接返回解析后的JSON对象
            const data = await response.json();
            
            // Reddit random接口返回的数组中第一个元素是目标帖子所在的列表
            const [postList] = data;
            const [post] = postList.data.children;
            
            const permalink = post.data.permalink;
            const memeUrl = `https://reddit.com${permalink}`;
            const memeImage = post.data.url;
            const memeTitle = post.data.title;
            const memeUpvotes = post.data.ups;
            const memeNumComments = post.data.num_comments;

            embed.setTitle(memeTitle);
            embed.setURL(memeUrl);
            embed.setColor('Random');
            embed.setImage(memeImage);
            embed.setFooter({
                text:`👍 ${memeUpvotes} 💬 ${memeNumComments}`
            });

            // 使用interaction.editReply更新回复
            await interaction.editReply({ embeds: [embed] });
        } catch (error) {
            console.error('获取帖子失败:', error);
            await interaction.editReply('获取搞笑帖子失败啦,请稍后再试!');
        }
    }
};

额外注意事项

  • User-Agent头:Reddit的API要求请求必须携带User-Agent,否则可能返回429(限流)或403(禁止访问)错误,需替换为你的机器人标识信息。
  • Slash命令响应:Discord要求slash命令必须在3秒内给出响应,因此需要先调用interaction.deferReply(),之后用interaction.editReply()更新内容。
  • 异常处理:添加try-catch块处理网络请求失败、API返回异常等情况,避免机器人崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 18:57:05