Max*_*678 3 javascript oauth node.js discord
我正在努力让不和谐的 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);
});
Run Code Online (Sandbox Code Playgroud)
文档:
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()
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助
小智 6
您的标题是:
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
Run Code Online (Sandbox Code Playgroud)
这意味着它还期望数据为表单数据而不是 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);
});
Run Code Online (Sandbox Code Playgroud)
您可以参考以下内容以更好地理解:https ://www.npmjs.com/package/node-fetch#post-with-form-parameters
| 归档时间: |
|
| 查看次数: |
4950 次 |
| 最近记录: |