首页 > 解决方案 > UnhandledPromiseRejectionWarning: DiscordHTTPError: 401 Unauthorized on GET /api/v7/users/@me

问题描述

我正在使用discord-oauth 包使用 Discord 制作登录系统......但它给出了未经授权的错误 (UnhandledPromiseRejectionWarning: DiscordHTTPError: 401 Unauthorized on GET /api/v7/users/@me)

代码:

const router = require('express').Router()
const crypto = require('crypto')
const DiscordOauth2 = require('discord-oauth2') 
const request = require('snekfetch')

const rateLimit = require('../middleware/limiterBotControler.js')
const baseUrl = 'https://discord.com/api/v7/'

const oauth = new DiscordOauth2({
    clientId: '782761260620972034',
    clientSecret: '',
    redirectUri: 'http://localhost:8080/login/discord/callback'
})

router.get('/login', (req, res) => {

    let url = oauth.generateAuthUrl({
        scope: ['identify', 'email', 'guilds'],
        state: crypto.randomBytes(16).toString('hex')
    })

    return res.redirect(url)
})

router.get('/login/discord/callback', (req, res) => {
    let code = req.query.code

    oauth.tokenRequest({
        code: code,
        grantType: 'authorization_code',
        scope: ['identify', 'email', 'guilds']
    }).then((refresh_token) => {
        oauth.getUser(refresh_token).then(console.log)
    })

标签: node.jsoauth-2.0callbackdiscord

解决方案


我自己也有类似的问题,虽然我很确定它与你的原因不同。这是我注意到的错误。

错误1)tokenRequest没有返回一个refresh_token,它返回的对象包含 { access_token, refresh_token, ...etc }

错误 2) getUser 使用 access_token,但是您正尝试使用 refresh_token 执行此操作

希望这会有所帮助^-^


推荐阅读