响应是 html 而不是 JSON?

问题描述 投票:0回答:1

我有一个很大的 JSON 文件,我希望实现一个小型 API,它可以从 JSON 文件中收集一些条目。我有如下所示。

现在我想要一个 JSON 响应,但是当我查询网站时得到的是(废话)HTML。在控制台中,我得到了 JSON,但这不是完整(正确)的响应,对吧......?如何让响应与html完全分离?

enter image description here

代码;

<!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>
json api response
1个回答
0
投票

您的 JavaScript 代码在浏览器中运行。您的浏览器接收 HTML,然后执行其中的脚本并在本地获取文件。

如果您希望在后端处理 JSON 文件,在将其发送给用户之前,您需要一个像 express.js

这样的服务器
© www.soinside.com 2019 - 2024. All rights reserved.