实现Discord登录调用OAuth2接口获access token遇unsupported_grant_type错误
Discord OAuth2 换取Access Token时出现
unsupported_grant_type错误的解决办法 你的问题核心是请求头与请求体格式不匹配:你指定了Content-Type: application/x-www-form-urlencoded,但却用JSON.stringify()把请求体转为了JSON格式,Discord的token接口无法识别这种矛盾的请求格式,因此返回错误。
以下是两种可行的修复方案:
方案一:使用表单编码格式的请求体(推荐)
保持application/x-www-form-urlencoded的请求头,将请求体转为表单编码格式:
const tokenResponseData = await request('https://discord.com/api/oauth2/token', { method: 'POST', data: new URLSearchParams({ client_id: config.clientId, client_secret: config.clientSecret, code: code, grant_type: 'authorization_code', redirect_uri: `http://localhost:3000/api/auth`, scope: 'identify', }).toString(), headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, });
方案二:改用JSON格式请求体
将请求头改为application/json,保持JSON格式的请求体(Discord接口支持此方式):
const tokenResponseData = await request('https://discord.com/api/oauth2/token', { method: 'POST', data: { client_id: config.clientId, client_secret: config.clientSecret, code: code, grant_type: 'authorization_code', redirect_uri: `http://localhost:3000/api/auth`, scope: 'identify', }, headers: { 'Content-Type': 'application/json', }, });
额外注意事项
- 确保
redirect_uri与Discord开发者平台中配置的授权回调地址完全一致,包括协议(http/https)、域名、端口和路径 - 检查
grant_type拼写正确,必须是authorization_code - 确认
client_id和client_secret没有复制错误或遗漏
内容的提问来源于stack exchange,提问作者SirGolem
相关产品推荐
相关产品推荐

