Node.js环境下通过Discord OAuth2获取用户名称的实现问题
问题排查与解决方法
1. 首先修复代码中的明显语法错误
你当前代码中使用的port变量未提前定义,会直接导致服务启动失败,需要先补充定义:
const port = process.env.PORT || 8080; // 端口可根据自身需求调整
2. 检查Discord OAuth基础配置
- 登录Discord开发者后台,确认你创建的应用OAuth2设置中的
Redirect URI和代码里写的https://oauth.aiueominato1111.repl.co完全一致,末尾多斜杠、协议不一致都会导致令牌请求失败 - 确认运行环境中
ci(对应客户端ID)、cs(对应客户端密钥)两个环境变量已正确配置,值和开发者后台给出的完全匹配
3. 补充请求状态校验,定位具体报错
你当前的代码没有对HTTP请求的响应状态做校验,哪怕请求返回400/401错误也会直接解析响应体,无法定位具体问题,调整后的完整代码如下:
const fetch = require('node-fetch'); const express = require('express'); const app = express(); // 补充端口定义 const port = process.env.PORT || 8080; app.get('/', async ({ query }, response) => { const { code } = query; if (code) { try { const oauthResult = await fetch('https://discord.com/api/oauth2/token', { method: 'POST', body: new URLSearchParams({ client_id: process.env['ci'], client_secret: process.env['cs'], code, grant_type: 'authorization_code', redirect_uri: `https://oauth.aiueominato1111.repl.co`, scope: 'identify', }), headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }); // 先校验令牌请求是否成功 if (!oauthResult.ok) { const errInfo = await oauthResult.json(); console.error('获取OAuth令牌失败:', errInfo); return; } const oauthData = await oauthResult.json(); const userResult = await fetch('https://discord.com/api/users/@me', { headers: { authorization: `${oauthData.token_type} ${oauthData.access_token}`, }, }); // 校验用户信息请求是否成功 if (!userResult.ok) { const errInfo = await userResult.json(); console.error('获取用户信息失败:', errInfo); return; } const userInfo = await userResult.json(); // 用户名就是userInfo.username,完整带辨识度的用户名为userInfo.username + '#' + userInfo.discriminator console.log('获取到的用户信息:', userInfo); console.log('完整用户名:', `${userInfo.username}#${userInfo.discriminator}`); } catch (error) { console.error('请求异常:', error); } } return response.sendFile('index.html', { root: '.' }); }); app.listen(port, () => console.log(`App listening at http://localhost:${port}`));
调整后运行代码,就可以在控制台看到具体的报错信息,或者正常打印出用户的用户名。
内容的提问来源于stack exchange,提问作者user48118
相关产品推荐
相关产品推荐

