如何修复Reddit API的Node.js请求中的unsupported_grant_type错误

时间:2019-03-26 21:38:29

标签: javascript node.js request reddit

向Reddit请求获取访问令牌时,我收到unsupported_grant_type错误。我正在尝试制作一个无需用户上下文即可发出API请求的应用。

我尝试过移动参数和标题,但无济于事。

这是我当前正在使用的代码(请注意,我的用户名=“我的客户ID”,密码=“我的秘密密钥”

var request = require("request");

var auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');

var options = { method: 'POST',
  url: 'https://www.reddit.com/api/v1/access_token',
  headers:
   { 'Content-Type': 'application/x-www-form-urlencoded',
   'Authorization': auth,
   },
  body: 
   JSON.stringify({grant_type: 'client_credentials',
     user: username,
     password: password})
};

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  console.log(response,body);
});

1 个答案:

答案 0 :(得分:0)

我确实以这种方式解决了这个问题。

我将标头'Content-Type': 'application/x-www-form-urlencoded'更改为Accept: 'application/json'。 主体没有将其设为JSON对象,而是将其作为字符串发送。 options.body = 'grant_type=client_credentials'

    const options = {};
        options.method = 'POST';
        options.headers = new Headers({
            'Accept-Language': 'en_US',
            Accept: 'application/json',
            Authorization: auth,
        });
    options.body = 'grant_type=client_credentials';
相关问题