1

I'm pretty sure this is caused by the JSON being empty but I'm trying to get the current song I'm playing on Spotify using node-fetch, any attempt at even calling response.json() causes the application to exit with this error:

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at Response.json (file:///C:/Users/44778/downloads/test/node_modules/node-fetch/src/body.js:149:15)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Here is my code:

fetch('https://api.spotify.com/v1/me/player/currently-playing', {
    method: 'GET', headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + accessToken
    }
}).then((response) => {
    try {
        console.log(response.json().then(
            (data) => { console.log(data) }
        ).catch((e) => { console.log(e)}));
    } catch (error) {
        console.log(error);
    }
});

1 Answers1

0

First of all, the proper way to write this that catches and logs all possible errors is this:

fetch('https://api.spotify.com/v1/me/player/currently-playing', {
    method: 'GET', headers: {
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + accessToken
    }
}).then((response) => {
    if (response.ok) {
        console.log(response.headers);
        return response.json();
    } else {
        throw new Error(`Got response.status: ${response.status}`);
    }
}).then(data => {
    console.log(data);
}).catch(e => {
    console.log(e);
});

With proper error handling and logging, this should tell you exactly where things are going haywire.

If you are still getting the rejection because of a JSON error, then check the logged response.headers to see if the content-type is application/json or not. You can also look in the network tab of the Chrome debugger and see exactly what the server is sending back to you, both for headers and body content. Or, for debugging purposes, if you change return response.json() to return response.text(), then the above code will log what the body is without trying to parse it.


Note: There is no point in sending 'Content-Type': 'application/json', with a GET request. The Content-Type on the request refers to the content-type of the body that you are sending. Since you are not sending a body with a GET, it is pointless to set that header. What you set the content-type to has nothing at all to do with what content-type the server will respond with. That may (or may not) be influenced by the "Accept" header (depending upon the server implementation for this route) which is the correct header to set to indicate you want JSON. But, obviously, the server has to cooperate and give you JSON.

jfriend00
  • 683,504
  • 96
  • 985
  • 979