原生JS fetch获取API返回JSON数组渲染HTML失效问题排查
问题根因
本地接口返回的解析结果是带data外层的对象,真正的用户数组存储在response.data属性上,不是直接返回数组。测试占位URL通常直接返回数组结构,因此原有遍历逻辑在测试地址下可正常运行,对接自有接口时直接遍历整个响应对象,自然无法正确读取用户数据。
此外接口返回的用户主键字段为_id而非id,拼接表格行时字段名不匹配也会导致单元格内容为空。
修复方案
- 传参给渲染方法时,传入解析结果的
data属性,不要直接传入整个响应对象 - 遍历拼接HTML时,字段名和接口返回结构对齐,主键读取
_id字段,若接口未返回email字段需替换为实际存在的属性(比如你提到的bet字段),或增加空值兜底 - 每次渲染前清空tbody节点原有内容,避免重复追加历史数据
参考实现代码
HTML结构
<table class="table table-bordered"> <thead> <tr> <th>Id</th> <th>Name</th> <th>Email</th> </tr> </thead> <tbody id="data"></tbody> </table>
原生JavaScript实现
function mostrarData(userList) { const tbody = document.getElementById('data'); // 清空旧内容 tbody.innerHTML = ''; // 遍历数组生成表格行 userList.forEach(user => { const tr = document.createElement('tr'); tr.innerHTML = ` <td>${user._id}</td> <td>${user.name}</td> <td>${user.email ?? '-'}</td> `; tbody.appendChild(tr); }); } fetch('http://localhost:3000/api/v1/users') .then(res => { if (!res.ok) throw new Error(`请求异常,状态码:${res.status}`); return res.json(); }) .then(res => { // 关键:传入res.data,即接口返回的用户数组 mostrarData(res.data); }) .catch(err => console.error('渲染异常:', err));
axios实现
注意axios会自动将响应体解析到自身返回对象的data属性上,因此接口返回的用户数组实际路径为res.data.data
axios.get('http://localhost:3000/api/v1/users') .then(res => { mostrarData(res.data.data); }) .catch(err => console.error('渲染异常:', err));
排查提示
调用渲染方法前可打印传入参数校验格式,如果打印结果为
{data: Array(2)}说明传参错误,必须传入纯数组类型的用户列表才能正常遍历。
内容的提问来源于stack exchange,提问作者Yamid Ortiz Muñoz
相关产品推荐
相关产品推荐

