spotify-web-api-node:authorizationCodeGrant()给出400 - 错误请求

时间:2017-12-26 21:39:58

标签: node.js express oauth spotify

我使用npm模块spotify-web-api-node来使用Spotify Web API,而无需编写大量代码。

我按照documentation给出的示例从Spotify获取授权码。然后,我使用此代码从Spotify获取访问令牌刷新令牌,并执行我想要的所有操作。

当我在此处询问访问令牌时会出现问题:

router.get('/auth/spotify/success', (req, res, next) => {
    let spotifyApi = new SpotifyWebApi({
        clientId: 'my-client-id',
        clientSecret: 'my-client-secret',
        redirectUri: 'http://localhost:3000/'
                 // The URI is registered to Spotify redirect URIs
    })

    const code = req.query.code

    spotifyApi.authorizationCodeGrant(code)
    .then(data => {
        console.log('The token expires in ' + data.body['expires_in'])
        console.log('The access token is ' + data.body['access_token'])
        console.log('The refresh token is ' + data.body['refresh_token'])

        // Set the access token on the API object to use it in later calls
        spotifyApi.setAccessToken(data.body['access_token'])
        spotifyApi.setRefreshToken(data.body['refresh_token'])


        res.render('index', { title: 'Connected !' })
    })
    .catch(err => {
        console.log('Something went wrong!', err);

        res.render('index', { title: 'Error !' })
    })
})

此代码记录:

Something went wrong! { [WebapiError: Bad Request] name: 'WebapiError', message: 'Bad Request', statusCode: 400 }

我的代码出了什么问题?如何从Spotify获取访问令牌和刷新令牌?谢谢!

1 个答案:

答案 0 :(得分:2)

问题很简单(我浪费了2天......)。正如Spotify API文档here中所述。 说到文档所说的redirect_uri参数:

TLDR请阅读:

  

此参数的值必须与请求授权代码时提供的redirect_uri的值完全匹配。

所以在我的代码中:

router.get('/auth/spotify/success', (req, res, next) => {
    let spotifyApi = new SpotifyWebApi({
        clientId: 'my-client-id',
        clientSecret: 'my-client-secret',
        redirectUri: 'http://localhost:3000/'
                 // Changing this...
        redirectUri: 'http://localhost:3000/auth/spotify/success'
                 // ...to this made it work !
    })

    // [...]

我也道歉,因为没有人能找到问题,因为我没有给你整个代码说“第一部分有效!”。是的,它有效,但它包含有关我的问题的有用线索。