Trying to utilize Spotify's Web Player API in order to retrieve the 'device_id' value has been a challenge. The documentation states that the server-side API call I am supposed to make should result in a 'json payload containing device objects', as shown below:
Below is my API call:
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);
});
});
Expected response:
{
"devices" : [ {
"id" : "5fbb3ba6aa454b5534c4ba43a8c7e8e45a63ad0e",
"is_active" : false,
"is_private_session": true,
"is_restricted" : false,
"name" : "My fridge",
"type" : "Computer",
"volume_percent" : 100
} ]
}
Error encountered:
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)
Although I can see the desired output by console.logging(body), I am unable to actually retrieve the specific value I need. Upon running my code, I receive an error indicating that body.devices is undefined. Any assistance on resolving this issue would be greatly appreciated. As a newcomer to express.js, could my routing be causing this problem?
Further update: I attempted res.json(body)... however, my server is returning an empty array of objects for 'devices'.