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

NodeJS - session information lost after building ReactJavaScript application

I've created a NodeJS web application with basic functionality for user login and pulling data from MySql based on session information. The app is functioning as intended (Link). However, when I implement the client-side in React, the session data is ...

Using Jquery for Animation: Tips on Revealing Text After Changing Element Color or Styles

Hey everyone, I ran into a bit of trouble while working with jQuery and trying out some animations. My goal was to make a textbox appear and display text when a button is highlighted, similar to a gallery setup. However, I managed to get halfway through th ...

Can I switch between different accounts on Auth0?

While utilizing next-auth for user sign-ins, I've noticed that there isn't a clearly visible option to switch accounts after signing in. Additionally, if users enter incorrect credentials, there doesn't seem to be a way to sign in with a dif ...

Unusual occurrence in Chrome when checking definitions: ReferenceError: x is not defined

Recently, I've come across some odd behavior in Chrome following its latest update. Whenever I try to determine if a variable is defined, it ends up triggering an uncaught error like the one shown below: if(x) { alert('x is defined.'); } T ...

Unable to supersede CSS module styling using global or external stylesheets in React, Next.js, or React Native

I'm facing a challenge finding a solution to a basic issue. I have a component that is initially styled using a class from a *.module.css file. However, I want to replace this style with one from a global stylesheet or another stylesheet but I can&apo ...

Is it feasible to preserve the HTML form content data even after refreshing the page?

Can someone offer a suggestion that doesn't involve using Ajax? I'm wondering if there is a way to achieve this using JavaScript/jQuery or some other method. Here's my issue: When submitting a page, the action class redirects back to the sa ...

"Implement image uploading and retrieval functionality in your application by utilizing Parse and Back4App with the help of Node

It seems like I have a question that may have already been answered, but I can't find the right solution for my issue. I'm facing trouble with my code and can't figure out what's wrong. The problem arises when I try to upload specific ...

Efficiently refresh several DIV elements with a single JSON request

After extensive searching, I've come to the conclusion that due to my limited proficiency in javascript, I need some help. The issue at hand is with a json format output produced by an ASP page on a separate webserver, which looks something like this: ...

Tips for validating a field by referencing data from a different model

I'm attempting to verify the validity of a date field by cross-referencing information stored in another model within the database. During API testing, the validation appears to work correctly as it triggers the exception, but the insertion actually ...

Navigating through JSON data that has been returned

When I use AJAX (jQuery) to query my database, the data I receive back is causing some difficulties. While searching for a solution, I came across similar issues posted by others who pointed out that the PHP code (specifically how data is stored in the arr ...

Angular JS Integration with PapaParse

Currently enjoying the efficiency of PapaParse's CSV parsing and unparsing features. Interested in integrating this with Angular JS - anyone able to assist with this integration? Excited about incorporating PapaParse into an Angular environment. Work ...

When importing a component that is passed as a prop in React, it is causing a blank page to render and is displaying an error in the

Visit this link for the code Everything was running smoothly with the app until I decided to include the Icon component in SidebarOption.js. Now, upon doing so, a blank page appears and an error is displayed in the console: An error occurred stating that ...

Transitioning React Hover Navbar Design

I'm currently revamping a click-to-open navbar into a hover bar for a new project. I have successfully implemented the onMouseEnter and onMouseLeave functions, allowing the navbar to open and close on mouse hover. However, I am facing an issue with ad ...

Edit the contents within HTML strings without altering the HTML structure

If I have a string of HTML, it might look something like this... <h2>Header</h2><p>all the <span class="bright">content</span> here</p> I am interested in manipulating the string by reversing all the words. For example ...

Setting up Laravel Mix Vue.js source maps to display actual component code during debugging

My current setup includes Laravel 5.4 and Vue.js 2.6. I'm facing an issue with viewing the sourceMap of *.vue component files in the console. Here is how I've configured Laravel mix: let mix = require('laravel-mix'); mix.webpackConfig ...

Unresolved CORS Issue in Vue.js Using Axios with undefined Proxy Response

My attempt to retrieve data using a client vueJS on port 8080 from the REST API on port 3000 is resulting in a CORSE Error. Interestingly, a successful POST operation occurs without any issues. To resolve this error, I followed the instructions provided in ...

Guide on redirecting a server URL to another URL when users access it through a static QR code

Can anyone help me with a dilemma I'm facing? I have static QR codes printed on thousands of boxes that direct to the wrong URL. The designer didn't make the code dynamic, so editing through the generator's interface is not an option. We ar ...

Getting row data in datatables after a button click: A step-by-step guide

Could somebody provide assistance with retrieving a single row of data on a click event? This table is dynamically populated after the AJAX call's Success function is executed <div class="table-responsive table-wrap tableFixHead container-flu ...

Incorporate a corner box feature to bring attention to the typed.js functionality

I have successfully integrated typed.js into my project and now I am looking to replicate the highlighted text with an excel-like box in one corner. I've managed to get the text typing out while also adding an SVG for the box in HTML, but I'm hav ...

Utilizing a Web Interface for Remote Monitoring of Windows Servers

I am in need of creating a webpage that will indicate whether a server is currently operational or not. These servers are all Windows based, with some running on 2008 and others on 2003. They are spread across different networks within various client locat ...