node.js - Spotify API 授权代码流程返回 'unsupported_grant_type' 错误

标签 node.js authentication spotify

我正在尝试使用 Node.js 应用程序访问 Spotify Web API。我已将 grant_type 指定为 authorization_code,但收到 unsupported_grant_type 错误,其描述为 grant_type 必须是 client_credentials、authorization_code 或 refresh_token

据我所知,我的 post 请求格式正确且值均正确。不确定还需要检查什么。

app.post('/auth', (req, res)=>{
  const auth = Buffer
                .from(`${process.env.CLIENT_ID}:${process.env.CLIENT_SECRET}`)
                .toString('base64');
  axios.post(token_uri, {}, {
      params: {
      'grant_type': 'authorization_code',
      'code': req.body.code,
      'redirect_uri': redirect_uri,
      client_id: process.env.CLIENT_ID,
      client_secret: process.env.CLIENT_SECRET
    }, headers: {
        'Authorization': `Basic ${auth}`,
        'Content-Type':'application/x-www-form-urlencoded'
      }
    })
    .then(res=>{
      console.log(res.data)
    })
    .catch(err=>{
      console.log(err)
    })
})

最佳答案

您正确设置了内容类型,但您以 JSON 格式而不是 x-www-form-urlencoded 格式发送数据。

以下 JSON 格式

      params: {
      'grant_type': 'authorization_code',
      'code': 'my_secret_code
    }

可以像这样转换为 x-www-form-urlencoded:

params = 'grant_type=authorization_code&code=my_secret_code'

尝试像这样更新您的请求:

  const params = 'grant_type=authorization_code&code=' + req.body.code
               + '&redirect_uri=' + redirect_uri
               + '&client_id=' + process.env.CLIENT_ID
               + '&client_secret=' + process.env.CLIENT_SECRET';

  axios.post(token_uri, 
    params,
    {
      headers: {
          'Authorization': `Basic ${auth}`,
          'Content-Type':'application/x-www-form-urlencoded'
        }
    })
    .then(res=>{
      console.log(res.data)
    })
    .catch(err=>{
      console.log(err)
    })

关于node.js - Spotify API 授权代码流程返回 'unsupported_grant_type' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49801190/

相关文章:

javascript - 如何将值添加到数组中的重复键中

php - 我正在尝试使用 php 建立一个简单的登录系统。它会运行,但您也可以使用错误的凭据登录。我究竟做错了什么?

javascript - Spotify App Preview API 访问 model.player 属性

javascript - 如何从 Angular 工厂发送带有循环的程序请求(一个接一个)?

javascript - 请求后等待在 JQuery 中发送另一个请求

node.js - 热推网站代码ala Meteor

node.js - Node JS 环境变量和 Heroku 部署

node.js - NPM 拒绝安装 Semantic-UI

security - Flink Web UI 身份验证

asp.net-mvc - 具有双因素和盲散列的 ASP.NET MVC4