I am trying to call Spotify API from Javascript like this:
function callAPI() {
var xhttp = new XMLHttpRequest();
xhttp.open('GET', 'https://api.spotify.com/v1/search?q=Muse&type=track');
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.setRequestHeader('Authorization', 'Bearer <MY_ACCESS_TOKEN>');
xhttp.send();
var response = JSON.parse(xhttp.responseText);
}
However, xhttp.responseText
is empty, although the request returns 200.
I can see in the browser that the request is returning the expected result but somehow I cannot extract it from the Javascript:
I tried calling the REST endpoint using Java (since I am more familiar with it) and that worked:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Test {
public static void main(String[] args) {
System.out.println("blah");
URL url = null;
try {
url = new URL("https://api.spotify.com/v1/search?q=Muse&type=track");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Bearer <MY_ACCESS_TOKEN>");
String responseMessage = connection.getResponseMessage();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer content = new StringBuffer();
try (reader) {
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
}
} finally {
reader.close();
}
System.out.println("Response: " + responseMessage);
System.out.println("Content: " + content.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am a Javascript newbie, so what am I doing wrong? Thanks a lot in advance!