spotify / web-api-examples

Basic examples to authenticate and fetch data using the Spotify Web API
Apache License 2.0
1.99k stars 1.67k forks source link

Web API auth examples use deprecated request library #55

Open doubledherin opened 4 years ago

doubledherin commented 4 years ago

Since the request library is now deprecated, it would be very helpful to update the examples to use node-fetch or some other library for each type of auth flow.

aleclawlor commented 4 years ago

^^ this would be helpful. Going to try with Axios later and will post if successful @doubledherin

aleclawlor commented 4 years ago

@doubledherin Here is a good thread I found. Currently referencing it now and it helps a lot

https://github.com/spotify/web-api/issues/1301

aleclawlor commented 4 years ago

Here's my new callback function using Express and Axios

app.get('/callback', (req, res) => {

const code  = req.query.code || null 
const state = req.query.state || null 
const storedState = req.cookies ? req.cookies[stateKey] : null 

if(state === null || state !== storedState){
    res.redirect('/#' + queryString.stringify({
        error: 'state_mismatch'
    }))
    return; 
}

res.clearCookie(stateKey)

axios({
    url: 'https://accounts.spotify.com/api/token',
    method: 'post',
    params: {
        code: code,
        redirect_uri: REDIRECT_URI,
        grant_type: 'authorization_code'
    },
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    auth: {
        username: CLIENT_ID,
        password: CLIENT_SECRET
    }
}).then(response => {
    console.log(response)

    const accessToken = response.data.access_token,
        refreshToken = response.data.refresh_token

    axios({
        url: 'https://api.spotify.com/v1/me',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        params: {
            access_token: accessToken,
            refresh_token: refreshToken
        }
    }).then(response => {
        // console.log(response)
        res.redirect('/#' + queryString.stringify({
            access_token: accessToken,
            refresh_token: refreshToken
        }))
    }).catch(err => {
        res.redirect('/#' + queryString.stringify({
            error: 'invalid token'
        }))
        console.log(err)
    })
}).catch(err => {
    console.log(err)
})

})