Even though the Spotify API JSON response may be undefined, I am still able to log it using console.log()

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'.

Answer №1

Your API is currently returning an empty response, possibly due to the use of res.end(). To ensure the correct JSON value from the Spotify API is being displayed, you should consider using res.json(...) instead of res.end(). In the code snippet below, we assume that the variable 'body' contains the necessary data:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

There has been an issue with displaying the static html content

This particular snippet of code seems to be causing some trouble for me: var app = require('express').createServer(); var ejs = require('ejs'); var fs = require('fs'); var indexTemplate = fs.readFileSync(__dirname + '/te ...

How can I create a dropdown menu that is dependent on another dropdown menu using Ajax in my Laravel application?

I have two dropdown fields that are dependent on each other - Class & Section. I am trying to Select * from sections where class_id=selected Class Id. Although I attempted to achieve this using java script, it doesn't seem to work for me. Here are ...

The functionality of the JavaScript animated placeholder seems to be malfunctioning

I am currently working on a code that updates the placeholder text every 2 seconds. The idea is to have it type out the letters one by one, and then erase them in the same manner. Unfortunately, the code is not functioning as expected. As a newcomer to J ...

Node.js offers a simple and effective way to redirect users to another page after they have

I am experiencing an issue when trying to redirect the client to the confirm page after a successful login process. I keep encountering some errors. view screenshot router.post('/sign_in', urlend, function(req, res) { var email = req.body.user ...

The ace.edit function is unable to locate the #javascript-editor div within the mat-tab

Having trouble integrating an ace editor with Angular material Error: ace.edit cannot locate the div #javascript-editor You can view my code on StackBlitz (check console for errors) app.component.html <mat-tab-group> <mat-tab label="Edito ...

Having trouble sending an HTTPS request in NodeJS only to receive an HTTP response instead

As I develop my website using NodeJS and deploy it on Heroku, I encountered an issue upon opening the website. Here is the problem at hand: When looking at the main source file of my web application: app.get('/', (req, res) => { var data ...

Refreshing the value of multiple radio buttons and sending them via AJAX

I have a group of radio buttons here. <input class='required' type='radio' name='Tbl' id='get_this1' value='tbl_a'> <input class='required' type='radio' name='Tbl' id ...

Tips for eliminating repetitive code in JavaScript

I have a jQuery function that deals with elements containing a prefix 'receive' in their class or ID names. Now, I need to duplicate this function for elements with the prefix 'send'. Currently, it looks like this: function onSelectAddr ...

I can't seem to figure out why I continue to receive the error message stating that 'app.get is not a function'

Below is the code I am currently using: const request = require('request'); const app = require('express'); app.get('/', function (req, res) { res.send('hello world'); }); app.listen(3000); Unfortunately, I keep e ...

Injecting dynamic variables into JSON objects using JavaScript

I am facing a challenge with populating values dynamically from an array of elements. Below is the primary array that I am working with. list = [{name: 'm1'}, {name: 'm2'},{name: 'm3'},{name: 'm4'},{name: 'm5&ap ...

What is causing the issue with transmitting the server datetime to my local jQuery script?

I am facing an issue with my timeoftheserver.php page setup. The PHP code is quite simple: <?php echo date('D, d M y H:i:s'); ?> Similarly, the script on my local machine is also straightforward: var today; try { today = new Date($. ...

Body Parser causing unexpected output

Currently encountering an issue when attempting to log the body of a POST request in my console. Despite seeing the payload in my Chrome console with the correct data, I am receiving the following error: express_1 | TypeError: Cannot read property ' ...

The dual-file upload feature of the jQuery ajaxForm plugin

After extensive searching online, I have yet to find an answer to my problem. The issue at hand is that when using the ajaxForm malsup plugin, it submits my files twice. HTML: <form id="gallery" enctype="multipart/form-data" action="/upload-gallery.p ...

Optimal Strategies for Interacting with a JSON REST API in Swift 2.0

As I transitioned to Swift, I quickly realized that a lot of the Sample Code I was using no longer functions in Swift 2.0. This has made it challenging for me as a beginner to navigate. I am seeking advice on the best practices for interacting with a REST ...

What is the quickest method to perform a comprehensive comparison of arrays and combine distinct objects?

I am currently working with NextJS and Zustand and I have a state in Zustand that consists of an array of objects: [{a:1, b:2}, {a:2, b:3}] Additionally, there is another incoming array of objects that contains some of the existing objects as well as new ...

Struggling with transferring information from JavaScript to PHP through the use of Ajax

Currently, I am working on creating a string using a JavaScript function and then passing it to PHP. This is the block of code in my JavaScript file: <script> function passVal(){ var strUrl = buildStringUrl(lat1, lng1, lat2, ...

Use jQuery to swap out two div classes within a table cell (TD) if they are

Although I'm making progress, I must confess that jQuery and CSS are not my strong suits. The objective: To create a dynamic div within a table data cell for a calendar feature. The content of the div varies based on the date range input. A filled d ...

Encountered a type error while attempting to render and define table columns within a material table component in

Hey there! I'm currently using the Material table to create a table view, and here are the columns that I have defined: const columns: TableColumn[] = [ { title: 'TYPE', field: 'type_of_action', highligh ...

Exploring ways to retrieve information stored in localStorage within an android mobile application

I am currently developing an Android App using phonegap. The app is a simple game that generates random numbers for math problems. If the user answers correctly, their score increases, but if they lose, their name and current score are saved in localStor ...

Is it possible to extract a specific value from JSON data by making an AJAX call or applying a filter to the fetched JSON data?

I have been utilizing a treeview template and successfully displaying all the data. However, I am facing an issue where I need to pass a value from index.php to getdata.php. I attempted using an AJAX filter on the index.php page and also tried sending a v ...