You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Reddit API获取Access Token时遇unsupported_grant_type错误求助

解决Reddit API OAuth获取Access Token时的"unsupported_grant_type"错误

问题核心是请求体格式与声明的Content-Type不匹配:你设置了Content-Type: application/x-www-form-urlencoded,但使用FormData作为请求体时,浏览器会自动将Content-Type改为multipart/form-data,而Reddit API仅接受application/x-www-form-urlencoded格式的请求体,因此返回unsupported_grant_type错误。

解决方案

使用URLSearchParams构建请求体(推荐),或手动拼接URL编码字符串,确保请求格式符合要求:

修改后的代码示例

async function fetchAccessToken(){
    console.log("fetching access token...");

    const cred = btoa(`${client_id}:${client_secret}`);

    // 用URLSearchParams构建符合x-www-form-urlencoded格式的请求体
    const params = new URLSearchParams();
    params.append('code', authCode);
    params.append('grant_type', grantType); // 务必确认grantType值为"authorization_code"
    params.append('redirect_uri', redirect_uri);

    const response = await fetch('https://ssl.reddit.com/api/v1/access_token', {
        method: 'POST',
        headers: {
            'Authorization': `Basic ${cred}`
            // 无需手动设置Content-Type,URLSearchParams会自动添加正确的Content-Type
        },
        body: params
    });

    const data = await response.json();

    console.log(response.status);
    console.log(data);
}

额外注意事项

  • 确认grantType变量的值是精确的字符串"authorization_code",没有拼写错误、大小写错误或额外空格
  • redirect_uri必须与授权流程中使用的地址完全一致,包括协议、域名、路径和结尾的斜杠等细节
  • 如果client_secret包含特殊字符,btoa可能无法正确编码,建议先对client_id和client_secret分别用encodeURIComponent处理后再拼接编码:
    const encodedClientId = encodeURIComponent(client_id);
    const encodedClientSecret = encodeURIComponent(client_secret);
    const cred = btoa(`${encodedClientId}:${encodedClientSecret}`);
    

内容的提问来源于stack exchange,提问作者Dschaar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 08:12:14