【问题标题】:Node JS trying to assign access token to a variableNode JS试图将访问令牌分配给变量
【发布时间】:2015-06-25 19:29:47
【问题描述】:

我是 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("My access token: "+access_token) 时,它说我的访问令牌未定义!这让我感到如此困惑的原因是相应的 HTML 文件,似乎发送访问令牌的地方,令牌显示得非常好!

有人知道我在这里做错了什么吗?我觉得我现在还没有很好地把握大局。

【问题讨论】:

  • 你能把你的body变量的内容粘贴到这里吗?

标签: javascript html node.js spotify


【解决方案1】:

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

body = JSON.parse(body);

设置access_tokenrefresh_token之前

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2021-06-11
    • 2016-10-15
    • 2014-05-13
    相关资源
    最近更新 更多