【发布时间】:2023-03-29 20:40:01
【问题描述】:
我正在创建一个 Discord 登录,但是当我被重定向时,我得到了错误。我在 Discord OAuth 页面上按授权后发生错误
{"status":"ERROR","error":"Response code 400 (Bad Request)"}
这是我的 Discord.js 代码
const express = require('express');
const router = express.Router();
const fetch = require('got');
const btoa = require('btoa');
const { catchAsync } = require('../utils');
const CLIENT_ID = '#';
const CLIENT_SECRET = '#';
const redirect = encodeURIComponent('https://ezapplications.live/api/discord/callback');
router.get('/callback', catchAsync(async (req, res) => {
if (!req.query.code) throw new Error('NoCodeProvided');
const response = await fetch(`https://discordapp.com/api/oauth2/authorize?client_id=${CLIENT_ID}&scope=identify&response_type=code&redirect_uri=${redirect}`, {
method: 'POST',
body: new URLSearchParams({
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
grant_type: "authorization_code",
redirect_uri: "https://ezapplications.live/api/discord/callback",
code: req.query.code
})
});
const json = await response.json();
res.redirect(`/?token=${json.access_token}`);
}));
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}`);
});
module.exports = router;
这是我的 Server.js 代码
const express = require('express');
const path = require('path');
const app = express();
app.get('/', (req, res) => {
res.status(200).sendFile(path.join(__dirname, 'index.html'));
});
app.use('/api/discord', require('./api/discord'));
app.use((err, req, res, next) => {
switch (err.message) {
case 'NoCodeProvided':
return res.status(400).send({
status: 'ERROR',
error: err.message,
});
default:
return res.status(500).send({
status: 'ERROR',
error: err.message,
});
}
});
app.listen(50451, () => {
console.info('Running on port 50451');
});
这里是 utils.js 的代码
// async/await error catcher
const catchAsyncErrors = fn => (
(req, res, next) => {
const routePromise = fn(req, res, next);
if (routePromise.catch) {
routePromise.catch(err => next(err));
}
}
);
exports.catchAsync = catchAsyncErrors;
我不知道为什么会出现这个错误,因为我觉得一切都很好,谢谢。
【问题讨论】:
标签: javascript node.js express discord