OAuth2:Discord API 始终响应 {"error": "invalid_grant"}

luk*_*lyz 5 javascript http oauth node.js discord

我正在尝试在我的node.js 应用程序中实现Discord OAuth2。一旦我尝试从给定的授权代码获取访问令牌,我总是会收到 HTTP 响应错误 400 {"error": "invalid_grant"}

let xhr = new XMLHttpRequest()
xhr.open('POST', 'https://discord.com/api/oauth2/token')

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')

let payload ={
    client_id: clientID,
    client_secret: clientSecret,
    grant_type: 'authorization_code',
    code: code,
    redirect_uri: redirectUrl,
    scope: 'identify'
};

console.log(payload)
xhr.send(JSON.stringify(payload))

xhr.onreadystatechange = () => {
    console.log(xhr.status)
    console.log(xhr.responseText)
}

xhr.onerror = () => {
    console.log('Failed')
}
Run Code Online (Sandbox Code Playgroud)

luk*_*lyz 3

好吧,我解决了这个问题。对于遇到与我相同问题的每个人,我通过使用 axios 和 querystring 将 POST 请求发送到 Discord API 来解决它(https://github.com/discord/discord-api-docs/issues/1131

看来JSON和x-www-form-urlencoded格式有问题。