0

discordのOAuth2を試しているのですがusernameの取り出し方がわからなく苦戦しています。
どなたか教えていただけませんか?

コード

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}`));
0

1 件の回答 1

0

質問文中のコード

console.log( await userResult.json());

で、ユーザ情報が node を実行したコンソールに出力されていると思います。

userResult から username だけ取り出すためのコードは次の通りです:

const resultJson = await userResult.json();
console.log(resultJson.username);

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。