Hey everyone! I’m having trouble with a JavaScript XMLHttpRequest call to a RapidAPI endpoint. The API seems to work fine when I test it with other tools, but my JavaScript implementation isn’t functioning as I expected.
Here’s the example code from RapidAPI for XMLHttpRequest:
var requestData = null;
var request = new XMLHttpRequest();
request.withCredentials = true;
request.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
request.open("GET", "https://music-extractor-api.p.rapidapi.com/download/abc123def");
request.setRequestHeader("x-rapidapi-host", "music-extractor-api.p.rapidapi.com");
request.setRequestHeader("x-rapidapi-key", "[API_KEY_HERE]");
request.send(requestData);
And here’s my implementation:
<!DOCTYPE html>
<html>
<head>
<title>API Test Page</title>
</head>
<body>
<h1>Testing RapidAPI Connection</h1>
<button onclick="fetchData()">Get API Data</button>
<div id="result"></div>
<script>
function fetchData() {
var apiRequest = new XMLHttpRequest();
apiRequest.withCredentials = true;
var endpoint = 'https://music-extractor-api.p.rapidapi.com/download/xyz789abc';
apiRequest.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200) || (this.readyState === this.DONE)) {
document.getElementById("result").innerHTML = "Response: " + this.responseText;
}
};
apiRequest.open("GET", endpoint);
apiRequest.setRequestHeader("x-rapidapi-host", "music-extractor-api.p.rapidapi.com");
apiRequest.setRequestHeader("x-rapidapi-key", "[MY_API_KEY]");
apiRequest.send();
}
</script>
</body>
</html>
The strange part is that the output shows "Response: " but no actual data follows. I’m receiving proper JSON error messages when I provide an invalid API key, indicating the connection is established. However, with a valid key, the responseText appears to be empty.
What could be causing this? Am I missing something in the request configuration?