首页 > 解决方案 > 如何修复对 Reddit API 的 nodejs 请求中的 unsupported_grant_type 错误

问题描述

我在向 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);
});

标签: javascriptnode.jsrequestreddit

解决方案


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

我将标题更改 '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';

推荐阅读