Hey everyone! I’m having trouble with making an XMLHttpRequest call to a RapidAPI endpoint. The API works fine when I test it with other tools, but my JavaScript code isn’t showing the response data.
Here’s what RapidAPI suggests:
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-downloader-api.p.rapidapi.com/audio/abc123def");
request.setRequestHeader("x-rapidapi-host", "music-downloader-api.p.rapidapi.com");
request.setRequestHeader("x-rapidapi-key", "your-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 Request</h1>
<button onclick="fetchData()">Get API Data</button>
<div id="result"></div>
<script>
function fetchData() {
var apiRequest = new XMLHttpRequest();
apiRequest.withCredentials = true;
var apiUrl = 'https://music-downloader-api.p.rapidapi.com/audio/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", apiUrl);
apiRequest.setRequestHeader("x-rapidapi-host", "music-downloader-api.p.rapidapi.com");
apiRequest.setRequestHeader("x-rapidapi-key", "your-api-key-here");
apiRequest.send();
}
</script>
</body>
</html>
When I click the button, I only see "Response: " without any actual data. If I use a wrong API key, I get an error message as expected. But with the correct key, the responseText seems empty. Any idea what might be wrong with my code?