首次创建MySQL+Node.js联系人管理项目遇‘Failed to load resource’错误
联系人管理项目前端脚本错误修复方案
核心问题与修复步骤
1. catch语句变量未定义报错
你的catch回调里引用了未声明的response变量,这会直接触发ReferenceError。catch的参数只有error,无法访问前面的response对象。
修复代码:
fetch('/data') .then(response => { // 先校验响应状态是否正常 if (!response.ok) { throw new Error(`请求失败:状态码 ${response.status}`); } return response.json(); }) .then(data => { // 表单赋值逻辑 }) .catch(error => console.log(error)); // 仅使用error变量
2. 后端返回数组,前端直接访问对象属性无效
后端SELECT * FROM contacts查询返回的是联系人对象数组,而非单个对象。你直接用data.firstname会得到undefined,因为数组不存在该属性。
修复分两种场景:
- 数据库仅存一条联系人数据,取数组第一个元素:
.then(data => { const contact = data[0]; if (contact) { document.querySelector(".firstname").value = contact.firstname; document.querySelector(".surname").value = contact.surname; document.querySelector(".phone").value = contact.phone; document.querySelector(".email").value = contact.email; document.querySelector(".firstline").value = contact.firstline; document.querySelector(".town").value = contact.town; document.querySelector(".county").value = contact.county; document.querySelector(".postcode").value = contact.postcode; } })
- 数据库有多条数据,循环生成列表(示例):
.then(data => { const list = document.querySelector('.contact-list'); data.forEach(contact => { const item = document.createElement('div'); item.innerHTML = `<h3>${contact.firstname} ${contact.surname}</h3><p>电话:${contact.phone}</p>`; list.appendChild(item); }); })
3. 可选:确保请求URL正确
如果前端页面运行端口和后端(5500)不一致,需使用完整请求地址:
fetch('http://localhost:5500/data')
验证流程
- 重启后端服务,确认控制台输出
Server listening at http://localhost:5500 - 打开浏览器开发者工具,在Network标签查看
/data请求的响应JSON是否正确 - 查看Console标签,确认无报错信息
内容的提问来源于stack exchange,提问作者Jack Shone
相关产品推荐
相关产品推荐

