简体   繁体   中英

Node JS trying to assign access token to a variable

I'm new to node.js and I'm trying to make spotify API requests but unfortunately getting an error with my access token variable.

I'm using the following code, basically taken word for word from their official example program:

var access_token;


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

// your application requests refresh and access tokens
// after checking the state parameter

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

if (state === null || state !== storedState) {
res.redirect('/#' +
  querystring.stringify({
    error: 'state_mismatch'
  }));
} else {
res.clearCookie(stateKey);
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) {

    access_token = body.access_token,
        refresh_token = body.refresh_token;

    var options = {
      url: 'https://api.spotify.com/v1/me',
      headers: { 'Authorization': 'Bearer ' + access_token },
      json: true
    };

    // use the access token to access the Spotify Web API
    request.get(options, function(error, response, body) {
      console.log(body);
    });

    // we can also pass the token to the browser to make requests from there
    res.redirect('/#' +
      querystring.stringify({
        access_token: access_token,
        refresh_token: refresh_token
      }));
  } else {
    res.redirect('/#' +
      querystring.stringify({
        error: 'invalid_token'
      }));
  }
});

}

So I have var access_token, and then I try to set access_token equal to body.access_token, which I'm assuming should be the value of the access token. However, when I run a console.log("My access token: "+access_token), it says my access token is undefined! The reason why this is so confusing for me is that the corresponding HTML file, where it seems to send the access token, the token shows up perfectly fine!

Does anybody know what I might be doing wrong here? I feel like I just don't grasp the big picture well enough right now.

The response body might be plain text and would need to be parsed. Try doing

body = JSON.parse(body);

before setting access_token and refresh_token

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM