I have been experimenting with fetching jokes using XMLHTTPRequest from a random joke generating API for practice.
Below is the code I am using:
<script>
const xhr = new XMLHttpRequest();
xhr.open('get', 'https://icanhazdadjoke.com/', true);
xhr.setRequestHeader('Accept', 'application/json')
const joke = JSON.parse(xhr.response)
xhr.onload = function () {console.log(xhr.responseText)}
xhr.send();
</script>
However, when I run this code, I encounter an error message: Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse ().
Interestingly, if I use JSON.parse(xhr.response) and save it to a variable, the script works without any issues. Can anyone spot what I might be doing wrong in my code?