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

Node.js调用Reddit API返回403错误,部分接口异常求排查

Node.js调用Reddit API部分接口返回403错误排查

我正在开发一个基于Node.js的Reddit API项目,目前遇到的问题是:调用部分API接口时返回403错误,但api/v1/me这类接口能正常使用。我需要使用下方的getPostScore和sendPrivateMessage函数,附上我的代码,请问哪里操作有误?

const axios = require('axios');

const redditClientID = 'the id'
const redditClientSecret = 'the secret'

module.exports = function(app) {
    app.get('/reddit', function(req, res) {
        res.redirect(`https://www.reddit.com/api/v1/authorize?client_id=${redditClientID}&response_type=code&state=RJIV5oTRU27BBNaPpqkU&redirect_uri=https://localhost:3000/reddit/callback&duration=temporary&scope=identity,submit,save,privatemessages,vote`)
    });

    app.get('/reddit/callback', (req, res) => {
        const code = req.query.code
        const encodedHeader = Buffer.from(`${redditClientID}:${redditClientSecret}`).toString("base64")
        axios ({
            method: 'post',
            url: `https://www.reddit.com/api/v1/access_token`,
            data: `grant_type=authorization_code&code=${code}&redirect_uri=https://localhost:3000/reddit/callback`,
            headers: {
                authorization: `Basic ${encodedHeader}`,
                'Content-Type': 'application/x-www-form-urlencoded',
                'User-Agent': 'web:PocArea:V0.1 by Me'
            }
        })
        .then((response) => {
            access_token = response.data.access_token
            console.log(access_token);
            getPostScore(access_token, "wxoezm")
        })
        .catch((err) => {
            res.status(500).json({ message: err });
        });
    })

    function getPostScore(redditKey, postId) {
        return axios({
            method: 'get',
            url: `https://oauth.reddit.com/api/info?id=${postId}`,
            headers: {
                'Authorization': `Bearer ${redditKey}`,
                'User-Agent': 'myBot/0.0.1'
            }
        })
        .then(response => {
            var resp = response.data;
            console.log(resp);
            return;
        })
        .catch(error => {
            console.error(`Error retrieving post ${postId} score: `, error);
        });
    }

    function sendPrivateMessage(redditKey) {
        axios({
            method: 'post',
            url: `https://oauth.reddit.com/api/compose`,
            data: {
                api_type: 'json',
                subject: 'objet du message privé',
                text: 'salut, voici un mp de la part de larea',
                to: 'KumaYes',
            },
            headers: {
                'Authorization': `Bearer ${redditKey}`,
                'User-Agent': 'myBot/0.0.1'
            }
        })
        .then((response) => {
            var resp = response.data;
            console.log(resp);
        })
        .catch((error) => {
            console.error(`Erreur lors de la récupération des issues du dépôt alaborde29/GithubAREA: `, error);
        });
    }
}

问题排查与修复方案

1. User-Agent不一致

Reddit API对请求的User-Agent有严格校验,必须保持全局一致且格式规范。你在获取access_token时用的是web:PocArea:V0.1 by Me,但后续两个接口请求里换成了myBot/0.0.1,这会触发403拦截。

修复:定义统一的User-Agent常量,所有请求复用:

const USER_AGENT = 'web:PocArea:V0.1 by /u/你的Reddit用户名'; // 替换为你的真实Reddit账号

然后将所有请求headers中的User-Agent值替换为这个常量。

2. 帖子ID格式错误

api/info接口要求帖子ID必须携带类型前缀t3_,你传入的wxoezm缺少前缀,导致接口无法识别目标资源,返回403。

修复:二选一即可:

  • 调用时传入完整ID:getPostScore(access_token, "t3_wxoezm")
  • 在函数内部自动补全前缀:url: https://oauth.reddit.com/api/info?id=t3_${postId}``

3. POST请求Content-Type错误

sendPrivateMessage是POST请求,你直接传入JSON格式的data,但Reddit API要求这类接口的Content-Type必须为application/x-www-form-urlencoded,默认的JSON格式会被拒绝。

修复:

  1. 安装qs库处理URL编码:
npm install qs
  1. 修改函数请求配置:
const qs = require('qs');

function sendPrivateMessage(redditKey) {
    axios({
        method: 'post',
        url: `https://oauth.reddit.com/api/compose`,
        data: qs.stringify({
            api_type: 'json',
            subject: 'objet du message privé',
            text: 'salut, voici un mp de la part de larea',
            to: 'KumaYes',
        }),
        headers: {
            'Authorization': `Bearer ${redditKey}`,
            'User-Agent': USER_AGENT,
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    // 后续代码保持不变
}

4. 未声明的全局变量(潜在问题)

在reddit/callback的回调中,access_token未用let/const声明,会变成全局变量,可能导致后续请求逻辑混乱。

修复:添加变量声明:

const access_token = response.data.access_token

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 21:33:26