I am serving a react app with an express server. The server talks to spotify’s api. My app was working fine before I implemented routing on reacts side.
var redirect_uri = 'http://localhost:8888/callback'; // Your redirect uri
app.use(express.static(path.join(__dirname, '../build')))
After login into spotify on spotify’s side, and upon successful login, a code is given back in a response query string with the redirect uri. So it would be http://localhost:8888/callback?code=blahblah-gibberish .
A get request is made to the /callback which hits the query string and takes the code from it and makes a post request to spotify’s service at https://accounts.spotify.com/api/token to exchange the code for an access token. That access token then lets us make requests to spotify’s endpoints
app.get('/callback', function(req, res) {
// your application requests refresh and access tokens
var code = req.query.code || null;
var state = req.query.state || null;
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
},
json: true
};
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
var access_token = body.access_token,
refresh_token = body.refresh_token;
// we can also pass the token to the browser to make requests from there
res.redirect('http://localhost:3000/#'+
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token
}));//this allows requests to come from front end from my understanding
//how do i make requests routes i define in the router. From what i have tried I can only have one
//redirect.
}
});
});
app.listen(8888);
Now for the part thats giving me issues:
res.redirect('http://localhost:3000/#'+
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token
}));
Before routing, all my components would load under http://localhost:3000. But after routing, when the react app is refreshed any time i make a change, data is no longer being received from the server side. So i am guessing the token needs to be given to every route from reacts side. From my understanding, now that i have implemented routing on the react side…:
<Route path="/playlist" component={Playlist} />
<Route path="/artist/:id" component={ArtistDetail} />
…the token would not be attached to say "localhost:3000/playlist because i only have a redirect for localhost:3000. How do I attach the access token and refresh token to my routes on the react/server side.
How do i get my routes to make requests? Like the server code said: // we can also pass the token to the browser to make requests from there . It passes the token to localhost:3000. How do I get it to pass the token to localhost:3000/whatever.