[英]Error redirect_uri: 'Not a well formed URL.' in discord OAuth2
I'm trying to do an OAuth2 for the discord, my code is this:我正在尝试为 discord 做一个 OAuth2,我的代码是这样的:
const express = require('express');
const fetch = require('node-fetch');
const btoa = require('btoa');
const { catchAsync } = require('../utils');
const querystring = require('querystring')
const router = express.Router();
const CLIENT_ID = '801791455034867723';
const CLIENT_SECRET = 'hehe :D, it\'s secret!';
const redirect = encodeURIComponent('http://localhost:50451/api/discord/callback');
router.get('/login', (req, res) => {
res.redirect(`https://discordapp.com/api/oauth2/authorize?client_id=${CLIENT_ID}&scope=identify&response_type=code&redirect_uri=${redirect}`);
});
router.get('/callback', catchAsync(async (req, res) => {
if (!req.query.code) throw new Error('NoCodeProvided');
const code = req.query.code;
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
const response = await fetch(`https://discordapp.com/api/oauth2/token`,
{
method: 'POST',
headers: {
Authorization: `Basic ${creds}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: querystring.stringify({
grant_type: 'authorization_code',
code: code,
redirect_uri: redirect
}),
}
);
const json = await response.json();
res.redirect(`/?token=${json.access_token}`);
}));
module.exports = router;
every time I run and give permission on the discord website, he gives this error: { redirect_uri: [ 'Not a well formed URL.'每次我在 discord 网站上运行并授予权限时,他都会给出此错误:{ redirect_uri: ['Not a well-formed URL.' ] }.
] }。
where did I go wrong?我在哪里 go 错了?
So your redirect variable is using the function "encodeURIComponent"所以你的重定向变量正在使用 function "encodeURIComponent"
const redirect = encodeURIComponent('http://localhost:50451/api/discord/callback');
Try using a variable that is that callback string, but without that function call尝试使用该回调字符串的变量,但没有该 function 调用
const redirect2 = 'http://localhost:50451/api/discord/callback'
I actually was following the same Medium article as you.我实际上和你关注的是同一篇 Medium 文章。 I think it was a bit outdated so the error occured.
我认为它有点过时了,所以发生了错误。
Then use redirect2 in your body然后在你的身体中使用redirect2
body: querystring.stringify({
grant_type: 'authorization_code',
code: code,
redirect_uri: redirect
}),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.