Hey everyone, I’m having trouble getting a RapidAPI call to work properly with vanilla JavaScript XMLHttpRequest. The API works fine when I test it through other methods, but my web implementation isn’t returning the expected data.
Here’s a working example I put together to demonstrate the issue:
<!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() {
const request = new XMLHttpRequest();
request.withCredentials = true;
const apiUrl = 'https://music-downloader5.p.rapidapi.com/download/abc123def';
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('result').innerHTML = 'Response: ' + this.responseText;
}
};
request.open('GET', apiUrl);
request.setRequestHeader('x-rapidapi-host', 'music-downloader5.p.rapidapi.com');
request.setRequestHeader('x-rapidapi-key', 'YOUR_API_KEY_HERE');
request.send();
}
</script>
</body>
</html>
The strange thing is that when I click the button, I only see the text 'Response: ’ without any actual API data. However, if I intentionally use a wrong API key, I do get an error message in JSON format. This makes me think the connection is working but something is wrong with how I’m handling the successful response. Any ideas what might be causing this behavior?