Node.js动态修改图片路径失败:请求排查并修正代码
Node.js动态加载图片失败的问题排查与修复
问题根源
你的HTTP服务器仅配置了/、/overview、/product这几个路由的处理逻辑,但浏览器请求图片时会发送/images/xxx.png这类请求,服务器没有对应的处理分支,最终返回错误页面,导致图片无法加载。
修复方案
在服务器中新增静态资源(图片)的处理逻辑,具体修改如下:
修改后的index.js代码
const fs = require('fs'); const http = require('http'); const url = require('url'); const path = require('path'); // 新增:用于安全处理文件路径 // Function to replace card const replaceTemplateCard = function (temp, fruit) { let output = temp.replace(/{%NAME%}/g, fruit.name); return output; }; const tempOverview = fs.readFileSync( `${__dirname}/templates/template-overview.html`, 'utf-8' ); const tempCard = fs.readFileSync( `${__dirname}/templates/template-card.html`, 'utf-8' ); const data = fs.readFileSync(`${__dirname}/data/fruits.json`, 'utf-8'); const dataObj = JSON.parse(data); //----- Server ----- const server = http.createServer((req, res) => { const { query, pathname } = url.parse(req.url, true); if (pathname === '/' || pathname === '/overview') { res.writeHead(200, { 'Content-type': 'text/html' }); const cardsHtml = dataObj .map((fruit) => replaceTemplateCard(tempCard, fruit)) .join(''); const output = tempOverview.replace('{%PRODUCT_CARDS%}', cardsHtml); res.end(output); } else if (pathname === '/product') { res.end('PRODUCT'); } else if (pathname.startsWith('/images/')) { // 新增:处理图片请求 // 构建本地图片文件的绝对路径 const imagePath = path.join(__dirname, pathname); // 检查图片文件是否存在 fs.access(imagePath, fs.constants.F_OK, (err) => { if (err) { // 文件不存在时返回404 res.writeHead(404, { 'Content-type': 'text/html' }); res.end('<h2>Image not found!</h2>'); return; } // 返回图片资源,设置正确的Content-Type res.writeHead(200, { 'Content-type': 'image/png' }); fs.createReadStream(imagePath).pipe(res); }); } else { res.writeHead(404, { 'Content-type': 'text/html' }); // 修正:错误页面返回404状态码 res.end('<h2>Page not found!</h2>'); } }); server.listen(8000, '127.0.0.1', () => { console.log('Listening to request on port 8000'); });
关键改动说明
- 引入
path模块:避免手动拼接路径时出现错误,确保路径跨平台兼容。 - 新增图片请求路由:通过
pathname.startsWith('/images/')识别图片请求,读取本地对应文件返回给浏览器。 - 文件存在性校验:用
fs.access检查图片是否存在,避免返回无效资源。 - 设置正确响应头:返回图片时指定
Content-type: image/png,让浏览器正确识别资源类型。 - 修正状态码:错误页面返回404状态码,符合HTTP规范。
额外检查项
确保项目目录下存在images文件夹,且里面的图片文件名(如apple.png)与fruits.json中的name字段完全对应。
内容的提问来源于stack exchange,提问作者user9623263
相关产品推荐
相关产品推荐

