感謝您的時間。我正在嘗試不和諧地使用 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}`));
謝謝你
uj5u.com熱心網友回復:
您已經擁有 JSON 資料(來自await userResult.json()),您可以從物件中獲取屬性或對其進行解構。
獲得財產
const user = await userResult.json();
const username = user.username
解構
const { username, id } = await userResult.json()
您可以從Discord 檔案中找到更多關于可以提取哪些屬性的資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/350392.html
