javascript - OAuth "unsupported_grant_type" Discord API
问题描述
我正在尝试使不和谐的 OAuth 工作。在文档中,需要生成代码,这一步效果很好,但是在生成令牌之后。它要求使用正确的参数发出 POST 请求,但它总是给我带来错误:{"error":"unsupported_grant_type"}
我的代码:
app.get('/discord/callback', async function (req, res) {
if (req.query.code === undefined || req.query.code == '') return next();
const response = await fetch("https://discordapp.com/api/v6/auth2/token", {
method: 'POST',
headers: {
"Content-type": "application/x-www-form-urlencoded"
},
data: {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
code: req.query.code,
redirect_uri: redirect,
grant_type: "authorization_code",
scope: "identify"
}
});
const json = await response.json();
debug('%O', json);
res.send(json);
});
文件:
def exchange_code(code):
data = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
'scope': 'identify email connections'
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
r = requests.post('%s/oauth2/token' % API_ENDPOINT, data, headers)
r.raise_for_status()
return r.json()
谢谢你的帮助
解决方案
你的标题是:
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
这意味着它还期望数据作为表单数据而不是 json。
所以这应该工作:
app.get('/discord/callback', async function (req, res) {
if (req.query.code === undefined || req.query.code == '') return next();
const params = new URLSearchParams();
params.append('client_id', process.env.CLIENT_ID);
params.append('client_secret', process.env.CLIENT_SECRET);
params.append('grant_type', 'authorization_code');
params.append('code', code);
params.append('redirect_uri', redirect);
params.append('scope', 'identify');
const response = await fetch("https://discordapp.com/api/v6/auth2/token", {
method: 'POST',
body: params
headers: {
"Content-type": "application/x-www-form-urlencoded"
},
});
const json = await response.json();
debug('%O', json);
res.send(json);
});
您可以参考这个以获得更好的理解:https ://www.npmjs.com/package/node-fetch#post-with-form-parameters
推荐阅读
- java - 使用多线程打印字母和数字
- c# - ASP.NET 表单 - 如何将表单数据发送到外部 WCF 服务
- angular - 如何订阅变量更改?
- javascript - 在 v-for 循环中将 textarea 的 v-model 绑定到 Vue.js 中的数组
- java - 为什么 JSTL fmt:formatNumber 根据值类型返回不同的结果?
- c# - 当绑定到“SelectedItem”时,如何让组合框设置 null 值?
- json - 使用带有 Unity IL2CPP 脚本后端的 JsonConvert.SerializeObject 的问题
- objective-c - 使用 @property 定义变量和在目标 c 中实现之间的区别
- mysql - SQL 内连接与 Sum
- javascript - JavaScript - 将 if 语句应用于节点列表/多个元素,而不仅仅是一个