Search code examples
javascriptoauthreddit

Trying to get images from Reddit using Javascript?


For this particular task, I have decided that it would be best if I were to use the Reddit API. Looking at the different wrappers available, I chose to use snoowrap. The examples are pretty clear, and I want to use something like this to get through authentication:

const snoowrap = require('snoowrap');

const otherRequester = new snoowrap({
    userAgent: 'put your user-agent string here',
    clientId: 'put your client id here',
    clientSecret: 'put your client secret here',
    username: 'put your username here',
    password: 'put your password here'
});

I can find the important information such as clientID and clientSecret on the Reddit Apps (Preferences Section). What confuses me, is the userAgent input. What exactly am I supposed to input here?

I thought I could go to Reddit OAuth Helper created by the same user. However, at the end of the process, I seem to get a Reddit Bad Request.


Solution

  • User agent is the browser where the request is being sent from:

    you can use the following command to populate that data:

    navigator.userAgent

    EDIT:

    The above will only work client side, on the server side if you're in a Nodejs(Expressjs) environment you can get the user agent from the headers data in the request parameter of your function executing your API call. Something like this:

    app.get('/api-call', function(request, response){
        const snoowrap = require('snoowrap');
    
        const otherRequester = new snoowrap({
            userAgent: request.headers['user-agent'], 
            clientId: 'put your client id here',
            clientSecret: 'put your client secret here',
            username: 'put your username here',
            password: 'put your password here'
        });
        // rest of the code
    });