Suplink
Suplink

Reputation: 71

Trying to get reddit's api to works in node JS, return error 403. where am i wrong?

I'm working on a node project that requires to use the reddit API.

My probleme here is that when i try to do a api call, it return 403.

The thing is that for some api routes, it works fine but not for thoses i want to use.

Here's my code :

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);
        });
    }
}

It works for routes like "api/v1/me" but for other routes i'm kinda lost.

I'll use the two function at the bottom (sendMessage and getPostScore)

Am I doing it wrong ?

Upvotes: 2

Views: 366

Answers (2)

Darkmode
Darkmode

Reputation: 1

Looking at the Code i have thought about something.

When looking at the error 403 its forbidden meaning you do not have the permissions to access the endpoint however deleting the cache and cookies aswell as checking if you are passing all of the neccecary parameters can help you solve the Problem.

Upvotes: -1

mhmmdamiwn
mhmmdamiwn

Reputation: 334

Looking at your code, it seems that you have properly authenticated your app with Reddit API by obtaining an access token. However, you are making a GET request to the api/info endpoint with a id parameter, which is returning a 403 error. This could be because you do not have sufficient permissions to access this endpoint with the scopes you have requested.

Upvotes: 0

Related Questions