shell
shell

Reputation: 1

Error when accessing (Discord)API with http.get()

My problem is I get a 301 error when accessing the Discord API(api/gateway).
In Postman(REST Client), it works fine:

enter image description here

But if I do it with my code, it always returns a 301 error:

function getGateway(){
    http.get({
        host: 'discordapp.com',
        path: '/api/gateway',
        headers: {
            'User-Agent': useragent //This is a variable.
        }
    }, function(res) {
        if (res.statusCode === 200) {
            var body = [];
            res.setEncoding('utf8');
            res.on('data', function(chunk) {
                body.push(chunk);
            });
            res.on('end', function() {
                body = body.join('');
                return body.url;
            });
        } else {
            if (res.statusCode === 429){
                setTimeout(function() {
                    getGateway();
                }, parseInt(JSON.parse(res.headers).Retry-After, 10) * 1000)
            } else {
                console.log('Received non-ok response: ' + res.statusCode);
            }
        }
    });
}

Output:

undefined
Received non-ok response: 301

Error code 301 is not even in the API documentation.
Can somebody see what I did wrong?

Upvotes: 0

Views: 910

Answers (1)

christophetd
christophetd

Reputation: 3874

The HTTP code 301 means that the URL you are trying to access was moved. One of the reasons may be that it automatically redirects to the HTTPS version of the API.

Unfortunately, it looks like the node http module doesn't handle following redirects. I would suggest one of these options:

  • use the awesome request module
  • find where the URL you are calling is trying to redirect you: the body of the response should contain information about this
  • use the follow-redirects module as a drop-in replacement for the http one, as described here

Upvotes: 1

Related Questions