Spotify Web Api/Axios/Heroku - POST Request 500 Error

Viewed 18

I was running my React project with a node/axios backend in my localhost with no errors. However, since deploying on Heroku, I can't seem to get my Axios POST requests to work, they give the errors seen below.

The useAuth hook, takes in the code okay from the url when the user signs in, pulling it from the url. But it fails to use the useAuth function/request to get an access token, refresh, and expires token on the axios POST request.

In Spotifys dashboard, my heroku urls are in the redirect uris.

Note: I'm hacking my way through debugging this and have little experience in using node/axios. So I may be unaware of things which may seem obvious and doing things which aren't possible - feel free to point them out.

In the client folder, useAuth.js.

    # The parameter code is as required in console
    console.log(code)
    useEffect(() => {
        axios.post('https://heroku-url-inserted-here.com/login', {
            code,
        })
        .then(res => {
            setAccessToken(res.data.accessToken)
            setRefreshToken(res.data.refreshToken)
            setExpiresIn(res.data.expiresIn)
            window.history.pushState({}, null, '/')
        })
        .catch((err) => {
            console.log("Error in Effect 1: " + err)
            console.log(err.response.data)
        })
    }, [code])

In server.js,

app.post('/login', (req, res) => { 
    const code = req.body.code;
    const spotifyApi = new spotifyWebApi({
        redirectUri: process.env.REDIRECT_URI,
        clientId: process.env.CLIENT_ID,
        clientSecret: process.env.CLIENT_SECRET,
    })

    spotifyApi.authorizationCodeGrant(code).then(data => {
        res.json({
            accessToken: data.body.access_token,
            refreshToken: data.body.refresh_token,
            expiresIn: data.body.expires_in
        })
    }).catch((err) =>{
        console.log(err)
        res.sendStatus(400)
    })
})

Error in console: 

Error in Effect 1: AxiosError: Request failed with status code 500
500 (Internal Server Error)

I'm hoping for the /login post to set and return the three tokens to set State, allowing major functionality to then work as it did when using local host.

1 Answers

ANSWER:

I was using a .env in my localhost testing environment but didn't set any config values within Heroku, as the .env is a part of the .gitignore file. This meant the redirectUri, clientId and clientSecret were all undefined in my server.js.

Configuring vars in Heroku sorted this issue: https://devcenter.heroku.com/articles/config-vars

Related