I’m having trouble getting my JavaScript XMLHttpRequest to work properly with a RapidAPI endpoint. The API call works fine when I test it through other methods, but my web implementation isn’t returning the expected data.
Here’s a working example from the API documentation:
const request = new XMLHttpRequest();
request.withCredentials = true;
request.addEventListener('readystatechange', function() {
if (this.readyState === 4) {
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();
And here’s my implementation:
<!DOCTYPE html>
<html>
<head>
<title>API Test</title>
</head>
<body>
<h1>API Request Test</h1>
<button onclick="fetchData()">Get Data</button>
<div id="result"></div>
<script>
function fetchData() {
const apiRequest = new XMLHttpRequest();
apiRequest.withCredentials = true;
const endpoint = 'https://music-downloader-api.p.rapidapi.com/audio/xyz789abc';
apiRequest.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('result').innerHTML = 'Response: ' + this.responseText;
}
};
apiRequest.open('GET', endpoint);
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 my placeholder text without any actual response data. If I use an invalid API key, I get proper error messages, so the connection is working. What could be causing the empty response when using a valid key?