Node.js服务器启动触发JSON解析错误,新手求助排查
问题排查与解决
错误根源
你把HTML文件的内容当成JSON数据解析了,这是核心问题:
- 代码中
data变量存储的是template-overview.html的HTML内容(开头是<!DOCTYPE...) - 却用
JSON.parse(data)尝试解析它,HTML不是JSON格式,自然触发语法错误
修正步骤
- 调整变量对应关系:把JSON文件的内容赋值给用于解析的变量,HTML文件对应到模板变量
- 修正API路由返回内容:/api接口应该返回JSON数据,而非HTML
- 补充overview页面的模板渲染逻辑(让页面正常展示产品卡片)
修正后的完整代码
const fs = require('fs'); const http = require('http'); const url = require('url'); // 修正:HTML模板对应正确变量 const tempOverview = fs.readFileSync('starter/templates/template-overview.html', 'utf-8'); const tempCard = fs.readFileSync('starter/templates/template-card.html', 'utf-8'); const tempProduct = fs.readFileSync('starter/templates/template-product.html', 'utf-8'); // 修正:JSON数据读取并解析 const dataJson = fs.readFileSync('starter/dev-data/data.json', 'utf-8'); const dataObj = JSON.parse(dataJson); const server = http.createServer((req, res) => { const pathName = req.url; // Overview页面:用模板渲染数据 if (pathName === '/' || pathName === '/overview') { res.writeHead(200, { 'Content-type': 'text/html' }); // 把数据填充到卡片模板 const cardsHtml = dataObj.map(item => { let card = tempCard; card = card.replace(/{%PRODUCTNAME%}/g, item.productName); card = card.replace(/{%IMAGE%}/g, item.image); card = card.replace(/{%PRICE%}/g, item.price); card = card.replace(/{%FROM%}/g, item.from); card = card.replace(/{%NUTRIENTS%}/g, item.nutrients); card = card.replace(/{%QUANTITY%}/g, item.quantity); card = card.replace(/{%DESCRIPTION%}/g, item.description); card = card.replace(/{%ID%}/g, item.id); return card; }).join(''); const output = tempOverview.replace('{%PRODUCT_CARDS%}', cardsHtml); res.end(output); // Product页面(可后续完善模板渲染) } else if (pathName === '/product') { res.end('This is our products:)'); // API接口:返回JSON数据 } else if (pathName === '/api') { res.writeHead(200, { 'Content-type': 'application/json' }); res.end(dataJson); // 404页面 } else { res.writeHead(404, { 'Content-type': 'text/html', 'My-own-header': 'Hello client' }); res.end('<h1>Page not found</h1>'); } }); server.listen(8000, '127.0.0.1', () => { console.log('The server is listening'); });
关键修正点说明
- 变量名调整:
data改为tempOverview,tempProduct改为dataJson,彻底避免文件类型混淆 JSON.parse的参数换成了真正的JSON文件内容dataJson,解决语法错误- /api路由返回
dataJson(原始JSON字符串),符合接口的JSON响应要求 - 补充了overview页面的模板渲染逻辑,匹配常见模板占位符的替换规则
内容的提问来源于stack exchange,提问作者Mamdouh Elhamy
相关产品推荐
相关产品推荐

