【问题标题】:Error when accessing (Discord)API with http.get()使用 http.get() 访问 (Discord)API 时出错
【发布时间】:2016-04-09 09:24:51
【问题描述】:

我的问题是访问 Discord API(api/gateway) 时出现 301 错误。
在 Postman(REST 客户端)中,它工作正常:

但如果我使用我的代码执行此操作,它总是会返回 301 错误:

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

输出:

undefined
Received non-ok response: 301

错误代码 301 甚至不在 API 文档中。
谁能看到我做错了什么?

【问题讨论】:

    标签: node.js api http get


    【解决方案1】:

    HTTP code 301 表示您尝试访问的 URL 已被移动。原因之一可能是它会自动重定向到 API 的 HTTPS 版本。

    不幸的是,节点http 模块似乎无法处理以下重定向。我会建议以下选项之一:

    • 使用很棒的request 模块
    • 查找您正在调用的 URL 试图将您重定向到哪里:响应的正文应包含有关此的信息
    • 使用follow-redirects 模块作为http 的直接替代品,如here 所述

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      • 2023-04-05
      相关资源
      最近更新 更多