我目前正在为 Discord OAuth2 实施开发后端并遇到问题。我尝试了几种方式来实现身份验证,但都没有用。
客户端在端口 3000 上运行,我的后端在端口 3001 上运行。当 discord 将您从身份验证返回到 http://localhost:3000 时,客户端正在从 discord 抓取代码并检查状态。然后使用代码向后端(http://localhost:3001/auth/discord)发送请求。然后执行以下代码:
import express from 'express';
import { readFileSync } from 'fs';
import axios from 'axios';
import btoa from 'btoa'
const router = express.Router();
const config = JSON.parse(readFileSync('config.json'));
router.post("/discord", async (req, res) => {
const { code } = req.body;
const data = {
'client_id': config['CLIENT_ID'],
'client_secret': config['CLIENT_SECRET'],
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': 'http://localhost:3001/auth/discord',
'scope': 'identify'
}
const tokenResponse = await axios.post(
'https://discord.com/api/oauth2/token',
data,
{headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}
)
.catch(e => e);
res.json(tokenResponse);
});
export { router as userRouter };
我还在 Discord 应用程序中添加了以下重定向 URI: http://localhost:3000/auth, http://localhost:3001/auth/discord, http://localhost:3000/auth/discord(我不知道我是否需要这个)
post请求抛出如下错误:
{
"message": "Request failed with status code 400",
"name": "AxiosError",
"stack": "AxiosError: Request failed with status code 400\n at settle (file:///C:/users/felix/desktop/valolytics/server/node_modules/axios/lib/core/settle.js:19:12)\n at IncomingMessage.handleStreamEnd (file:///C:/users/felix/desktop/valolytics/server/node_modules/axios/lib/adapters/http.js:556:11)\n at IncomingMessage.emit (node:events:525:35)\n at endReadableNT (node:internal/streams/readable:1359:12)\n at process.processTicksAndRejections (node:internal/process/task_queues:82:21)",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"adapter": [
"xhr",
"http"
],
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": "axios/1.3.4",
"Content-Length": "217",
"Accept-Encoding": "gzip, compress, deflate, br"
},
"method": "post",
"url": "https://discord.com/api/oauth2/token",
"data": "client_id=1000000000000000000&client_secret=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&grant_type=authorization_code&code=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&redirect_uri=http%3A%2F%2Flocalhost%3A3001%2Fauth%2Fdiscord&scope=identify"
},
"code": "ERR_BAD_REQUEST",
"status": 400
}
我尝试了几种不同的 post 请求实现,都导致了这个 400 Bad Request 错误。谁能帮我这个?这么多TY<3