It is supposed to get all the guilds a user is joined in. It gets the bearer auth right, but it always errors with code 401. When using a external API (https://reqbin.com/) with auth to test the discord API it also gives the same error 401.
This is the code:
let discordCode = window.location.href
let code = discordCode.split("?code=")
if(code && code.length > 0){
discordCode = code[code.length-1]
}
console.log(discordCode)
fetch("https://discord.com/api/users/@me/guilds",{method: 'GET',headers: {
"Authorization": `Bearer ${discordCode}`,
}}).then(function(response) {
response.json().then((result) => {
console.log(result)
})
})
/*fetch(`/discordProxy/${discordCode}`).then(function(response) {
response.json().then((result) => {
console.log(result)
})
})*/
$("#connect_top_button").click(function(){
window.location.href = "https://discord.com/api/oauth2/authorize?client_id=955915443405729844&redirect_uri=http%3A%2F%2F130.162.37.209%2Fservers&response_type=code&scope=identify%20guilds"
})
The oauth2 scopes I gave to the app are: identify, email, guilds
Edit: Actually, it seems that all the auth tokens from the oauth2 don't work. Weird
You must get discord token and use it in authorization:
"Authorization": `Bearer ${await getTokenDiscord()}`
here is my example of getting the discord token:
async getTokenDiscord() {
const params = new URLSearchParams()
params.append('client_id', CLIENT_ID)
params.append('client_secret', CLIENT_SECRET)
params.append('grant_type', 'authorization_code')
params.append('code', YOUR_DISCORD_CODE)
params.append('redirect_uri', REDIRECT_URL)
params.append('scope', 'identify')
const resp = await fetch('https://discord.com/api/oauth2/token', {
method: 'post',
body: params,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json'
}
})
return await resp.json()
}
It's not the best example of how to do this, but it's the way it works for me