Search code examples
javascriptjsonresponse

Response is html and not JSON?


I have a large JSON file and I wish to implement a small API which collects some entries from the JSON file. I have the following as shown below.

Now I would like to have a JSON response, but what I get when I query the site is (duh) the HTML. In the console I get the JSON, but that isn't a full (correct) response right...? How can I let the response be completely separate from the html?

enter image description here

Code;

<!DOCTYPE html>
<html>
<head>
  <title>Glossary API</title>
</head>
<body>
  <script>
    function fetchData() {
        const urlParams = new URLSearchParams(window.location.search);
        const term = urlParams.get('term');
        const abbr = urlParams.get('abbr');
        
        if (!abbr && !term) {
            console.error('Both abbreviation and term parameter is missing. Either one or both is needed.');
            return;
        }
        if (!abbr)
            console.warn('Abbreviation parameter is missing.');
        
        if (!term)
            console.warn('Term parameter is missing.');
        
        fetch('data/glossary.json', 
            {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                const result = data.filter(
                    item => ((item.abbreviation.toString().match(abbr) && abbr) || 
                             (item.term.toString().match(term) && term))
                )
                
                if (!result) {
                    console.error('Abbreviation or definition not found');
                    return;
                }
                // Display the result on the page as JSON
                console.log(JSON.stringify(result, null, 2))
                document.body.innerHTML = JSON.stringify(result, null, 2);
            })
            .catch(error => console.error('Error fetching data:', error));
    }

    fetchData();
  </script>
</body>
</html>

Solution

  • Your JavaScript code runs in the browser. Your browser receives HTML, then executes the script inside and fetches the file locally.

    If you wish to process the JSON file in the backend, before sending it to the user, you'll need a server like express.js