【问题标题】:Spotify API - JSON returns undefined, but I can still console.log() itSpotify API - JSON 返回未定义,但我仍然可以 console.log() 它
【发布时间】:2020-03-28 22:39:11
【问题描述】:

我正在尝试使用 Spotify 的 Web Player API 来访问值“device_id”。根据文档,我进行的服务器端 API 调用应该返回一个“包含设备对象的 json 有效负载”,如下所示:

这是我的 API 调用:

app.get('/c+party', (req,res)=>{
    const access_token = req.query.access_token;
    var device_id;
    var options = {
        url: 'https://api.spotify.com/v1/me/player/devices',
        headers: {
            'Authorization': 'Bearer '+ access_token,
            'Content-Type':'application/json'
        },
        json:true
    };
    request.get(options, (err,response,body) => {
        const device_id = body.devices[0].id;
        res.json(device_id);
    });
});

它应该返回:

{
  "devices" : [ {
    "id" : "5fbb3ba6aa454b5534c4ba43a8c7e8e45a63ad0e",
    "is_active" : false,
    "is_private_session": true,
    "is_restricted" : false,
    "name" : "My fridge",
    "type" : "Computer",
    "volume_percent" : 100
  } ]
}

编辑,这是错误:

const device_id = body.devices[0].id;
                                          ^

TypeError: Cannot read property 'id' of undefined
    at Request._callback (C:\code\music-room\src\server.js:69:43)
    at Request.self.callback (C:\code\music-room\node_modules\request\request.js:185:22)
    at Request.emit (events.js:223:5)
    at Request.<anonymous> (C:\code\music-room\node_modules\request\request.js:1154:10)
    at Request.emit (events.js:223:5)
    at IncomingMessage.<anonymous> (C:\code\music-room\node_modules\request\request.js:1076:12)
    at Object.onceWrapper (events.js:312:28)
    at IncomingMessage.emit (events.js:228:7)
    at endReadableNT (_stream_readable.js:1185:12)
    at processTicksAndRejections (internal/process/task_queues.js:81:21)

我可以通过 console.log(body) 查看所需的输出,但实际上我无法访问我想要的值。当我的代码运行时,我收到 body.devices 未定义的错误。对修复有任何帮助吗?我是 express.js 的新手 - 我的路由是否搞砸了?

另一个编辑:我尝试了 res.json(body)...我的服务器正在响应一个空的“设备”对象数组。

【问题讨论】:

  • 你能显示body变量的内容吗?
  • 当我记录 body 变量时,它完全符合预期(我的帖子中的 JSON)

标签: javascript json express spotify


【解决方案1】:

您实际上是从您的 API 发回一个空响应。这就是res.end() 所做的。我不完全确定 Spotify API 响应的内容是什么,但如果您可以在 body 变量中看到正确的 JSON 值,您可以使用 res.json(...) 而不是 res.end(),如下所示:

request.get(options, (err,response,body) => {
 // Assuming that the body variable contains the correct data
 const device_id = body.devices[0].id;
 res.json(device_id);
});

【讨论】:

  • 我实际上已经尝试过 res.json(),但最终得到了相同的结果。我认为问题在于尝试将 id 分配给“device_id”(即使我可以将其记录到控制台......)。我编辑了我的帖子以分享我所看到的。
  • 您确定 Spotify API 响应的数据正确吗?据我所知,它不会返回任何设备。
猜你喜欢
  • 1970-01-01
  • 2019-02-14
  • 1970-01-01
  • 1970-01-01
  • 2018-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多