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

使用Fetch调用Reddit API创建评论遇403及Body解析错误求助

解决Reddit API评论接口403禁止与Body解析错误

问题根源及修复步骤

  • Content-Type与请求体格式不匹配:Reddit的/api/comment接口要求使用*application/x-www-form-urlencoded*格式提交参数,而非JSON。你当前用JSON.stringify生成请求体并设置Content-Type: application/json,这会导致接口无法解析参数,触发403错误。
  • Accept头设置错误:接口返回JSON数据,不应设置Accept: text/html,需改为*application/json*。
  • 多余请求头干扰:Sec-Fetch-*系列头是浏览器自动生成的请求头,手动添加会触发Reddit的安全校验,直接移除即可。
  • Body重复读取导致异常:错误处理中先调用response.text()读取响应体,之后又调用response.json(),而Response的body只能被消费一次,这就会抛出Body is unusable错误。

修正后的完整代码

async function commentOnRedditPost(postId, commentText, accessToken) {
  const url = `https://oauth.reddit.com/api/comment`;
  const params = new URLSearchParams();

  console.log("access_token:", accessToken, postId, commentText);

  params.append("api_type", "json");
  params.append("thing_id", postId);
  params.append("text", commentText);

  const response = await fetch(url, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/x-www-form-urlencoded",
      Accept: "application/json",
      "User-Agent": "profullstack comment bot v1.0",
    },
    mode: "cors",
    body: params,
  });

  const responseText = await response.text();
  if (!response.ok) {
    console.error(responseText);
    throw new Error(`Failed to comment on Reddit post ${postId}: ${responseText}`);
  }

  return JSON.parse(responseText);
}

额外注意事项

  • 确保accessToken拥有submit权限,并且令牌未过期。
  • postId需要带上前缀(比如t3_1cxbmk6),Reddit的thing_id要求格式为{type}_{id},帖子对应的前缀是t3_,评论是t1_。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 20:42:42