【问题标题】:Extracting values from API data in node.js从 node.js 中的 API 数据中提取值
【发布时间】:2021-12-19 23:14:46
【问题描述】:

感谢您的宝贵时间。 我正在尝试在不和谐中使用 OAuth2,但我很难弄清楚如何检索用户名。 谁能告诉我怎么做?

代码

const fetch = require('node-fetch');
const express = require('express');

const app = express();

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',
                },
            });

            const oauthData = await oauthResult.json();

            const userResult = await fetch('https://discord.com/api/users/@me', {
                headers: {
                    authorization: `${oauthData.token_type} ${oauthData.access_token}`,
                },
            });
            console.log( await userResult.json());
        } catch (error) {
            // NOTE: An unauthorized token will not throw an error;
            // it will return a 401 Unauthorized response in the try block above
            console.error(error);
        }
    }

    return response.sendFile('index.html', { root: '.' });
});

app.listen(port, () => console.log(`App listening at http://localhost:${port}`));

谢谢

【问题讨论】:

    标签: node.js api oauth-2.0 discord


    【解决方案1】:

    您已经拥有 JSON 数据(来自 await userResult.json()),您可以从对象中获取属性或对其进行解构。

    获取财产

    const user = await userResult.json();
    const username = user.username
    

    解构

    const { username, id } = await userResult.json()
    

    您可以详细了解可以从Discord documentation 中提取哪些属性

    【讨论】:

      猜你喜欢
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2020-10-22
      • 2023-03-13
      • 2011-10-19
      • 2013-06-14
      • 1970-01-01
      相关资源
      最近更新 更多