节点JS尝试将访问令牌分配给变量

时间:2015-04-19 01:17:35

标签: javascript html node.js spotify

我是node.js的新手,我试图发现Spotify API请求,但遗憾的是我的访问令牌变量出错了。

我使用以下代码,基本上是从他们的官方示例程序中逐字逐句:

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'
      }));
  }
});

}

所以我有var access_token,然后我尝试将access_token设置为body.access_token,我假设它应该是访问令牌的值。但是,当我运行console.log("我的访问令牌:" + access_token)时,它表示我的访问令牌未定义!这对我来说如此混乱的原因是相应的HTML文件,它似乎发送访问令牌,令牌显示完全正常!

有人知道我在这里做错了什么吗?我觉得我现在还不能很好地掌握整体情况。

1 个答案:

答案 0 :(得分:1)

响应正文可能是纯文本,需要进行解析。尝试做

body = JSON.parse(body);

在设置access_tokenrefresh_token

之前
相关问题