如何让基于JSON文件的API返回纯JSON响应而非HTML?
如何让基于JSON文件的API返回纯JSON响应而非HTML
我有一个大型JSON文件,想实现一个小型API用来从中提取部分条目。现在访问查询站点时,响应是HTML格式,只能在控制台看到JSON内容,请问怎么让响应完全脱离HTML,直接返回纯JSON?
当前使用的代码:
<!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>
解决方案
你当前的实现是前端HTML页面通过浏览器端JS读取并处理JSON,服务器返回的始终是HTML文档,所以响应本质还是HTML。要返回纯JSON,必须用后端服务直接生成并返回JSON格式的响应,以下是两种简单可行的实现方式:
方法一:Node.js + Express
- 初始化项目并安装依赖:
npm init -y npm install express
- 创建
server.js文件:
const express = require('express'); const fs = require('fs'); const app = express(); const port = 3000; // 预读取JSON文件(缓存起来避免重复IO操作) const glossaryData = JSON.parse(fs.readFileSync('./data/glossary.json', 'utf8')); app.get('/api/glossary', (req, res) => { const { term, abbr } = req.query; // 参数校验 if (!term && !abbr) { return res.status(400).json({ error: '必须提供term或abbr参数中的至少一个' }); } // 筛选匹配条目 const result = glossaryData.filter(item => { const matchesAbbr = abbr ? item.abbreviation.toString().includes(abbr) : false; const matchesTerm = term ? item.term.toString().includes(term) : false; return matchesAbbr || matchesTerm; }); // 无匹配结果处理 if (result.length === 0) { return res.status(404).json({ error: '未找到匹配的缩写或术语' }); } // 返回纯JSON响应 res.json(result); }); app.listen(port, () => { console.log(`API服务运行在 http://localhost:${port}`); });
- 启动服务:执行
node server.js,之后访问http://localhost:3000/api/glossary?term=你的术语或http://localhost:3000/api/glossary?abbr=你的缩写即可得到纯JSON响应。
方法二:Python Flask
- 安装Flask依赖:
pip install flask
- 创建
app.py文件:
from flask import Flask, request, jsonify import json app = Flask(__name__) # 预读取JSON文件 with open('./data/glossary.json', 'r', encoding='utf8') as f: glossary_data = json.load(f) @app.route('/api/glossary') def get_glossary(): term = request.args.get('term') abbr = request.args.get('abbr') # 参数校验 if not term and not abbr: return jsonify({'error': '必须提供term或abbr参数中的至少一个'}), 400 # 筛选匹配条目 result = [] for item in glossary_data: matches_abbr = abbr and str(item['abbreviation']).find(abbr) != -1 matches_term = term and str(item['term']).find(term) != -1 if matches_abbr or matches_term: result.append(item) # 无匹配结果处理 if not result: return jsonify({'error': '未找到匹配的缩写或术语'}), 404 # 返回纯JSON响应 return jsonify(result) if __name__ == '__main__': app.run(port=3000, debug=True)
- 启动服务:执行
python app.py,访问方式与Node.js版本一致。
内容的提问来源于stack exchange,提问作者WG-
相关产品推荐
相关产品推荐

