必须通过http服务(如live server或http-server)访问html文件才能用fetch加载本地json,否则因file://协议受安全限制而失败;解析后应使用textcontent或dom方法渲染以防xss,避免innerhtml拼接。

JSON 文件用 fetch() 加载时 404 或跨域失败
本地直接双击打开 HTML 文件时,浏览器会以 file:// 协议运行,此时 fetch('./data.json') 实际请求的是本地文件路径,但现代浏览器出于安全限制会拒绝加载(报 net::ERR_FAILED 或 CORS error)。必须通过 HTTP 服务访问——哪怕只是本地启动一个最小服务。
实操建议:
- 用 VS Code 安装
Live Server插件,右键 HTML 文件点「Open with Live Server」 - 或终端执行
npx http-server(需先npm install -g http-server),然后访问http://127.0.0.1:8080 - 确保
data.json和 HTML 在同一目录下,且 JSON 格式合法(末尾无逗号、字符串用双引号)
解析 JSON 后渲染到页面的常见写法
不要把 JSON 当字符串拼接进 innerHTML,尤其当数据含用户输入内容时,有 XSS 风险。推荐用 DOM 方法逐个创建元素,或用 textContent 赋值。
示例:假设 data.json 是 {"name": "Alice", "age": 30}
fetch('data.json')
.then(r => r.json())
.then(data => {
document.getElementById('name').textContent = data.name;
document.getElementById('age').textContent = data.age;
});
如果要渲染数组,比如 [{"id":1,"title":"A"},{"id":2,"title":"B"}],用 forEach 创建 <li> 更安全:
data.forEach(item => {
const li = document.createElement('li');
li.textContent = item.title;
document.getElementById('list').appendChild(li);
});
遇到 Unexpected token N in JSON at position 0 怎么办
这通常不是 JSON 本身问题,而是 fetch 返回了 HTML(比如 404 页面)或空响应,却被强行 .json() 解析。Node.js 后端返回非 JSON 内容、Nginx 配置错误返回 50x 页面、甚至 JSON 文件开头有 BOM 字节,都可能触发这个错。
排查步骤:
- 在
.then(r => { console.log(r.headers.get('content-type')); })看响应头是否为application/json - 加
.then(r => r.text()).then(console.log)打印原始响应体,确认是不是 HTML 或空字符串 - 用 VS Code 以「UTF-8 无 BOM」格式保存 JSON 文件(右下角点击编码 → 「Save with Encoding」→ 「UTF-8」)
JSON 嵌套深、结构不确定时怎么安全取值
别直接链式访问 data.user.profile.avatar.url,一环为 undefined 就报错。用可选链操作符 ?.(ES2020+)最简洁:
const avatar = data?.user?.profile?.avatar?.url;
if (avatar) {
imgEl.src = avatar;
}
兼容老浏览器?改用逻辑判断:
const avatar = data && data.user && data.user.profile && data.user.profile.avatar && data.user.profile.avatar.url;
或者封装一个安全取值函数:
function get(obj, path, defaultValue) {
return path.split('.').reduce((cur, key) => cur?.[key], obj) ?? defaultValue;
}
// 用法:get(data, 'user.profile.avatar.url', '/default.png')
深层嵌套 + 循环渲染时,务必检查每层是否存在,否则页面直接白屏。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











