Making API calls to RapidAPI using native JavaScript XMLHttpRequest

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?

yep, sounds like it might be an empty response or smth with the content-type. try adding some console.logs to see what you’re actually getting back. also, the network tab in dev tools can be super helpful for figuring this stuff out!

I’ve hit this same issue with RapidAPI endpoints. You’re probably only checking for status 200, but some APIs send data with 202 or 204 codes, or return empty bodies for certain endpoints. First, log everything regardless of status - just use if (this.readyState == 4) and console.log both status and responseText. That music downloader endpoint might need extra parameters or have no data for your test ID. I’d test with a simpler RapidAPI endpoint first to make sure your code actually works.

Sounds like a CORS issue or maybe that endpoint’s returning binary data instead of text. I’ve hit this before with media APIs where you get a file stream back, not JSON. First thing - ditch the withCredentials = true line. RapidAPI usually doesn’t need credentials and it often breaks CORS. Also double-check if that endpoint wants extra query parameters or if it’s actually returning file data. Quick test: try a different RapidAPI endpoint to make sure your XMLHttpRequest setup works.