You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js加载static/home/done目录图片遇404错误的解决求助

解决方法

1. 启用Express目录浏览功能

你遇到的404本质是Express的express.static默认不提供目录索引(即访问目录时不返回文件列表),直接请求/static/home/done/会返回404。需要借助serve-index中间件实现目录浏览:

  • 先安装依赖:
npm install serve-index
  • 修改server.js,引入并配置中间件:
const express = require('express');
const serveIndex = require('serve-index'); // 新增引入
const app = express();

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/template/home.html');
});

// 替换所有重复的静态路由,只保留这一行:既处理静态文件,又启用目录浏览
app.use('/static/home', express.static('static/home'), serveIndex('static/home', { icons: true }));

app.listen(4400, () => {
    console.log('Server running on http://127.0.0.1:4400');
});

2. 清理重复路由

原来的server.js里重复配置了多组静态路由,会导致路径解析冲突,必须删掉这些冗余配置:

// 删掉以下重复的路由
// app.use(express.static('static/home'));
// app.use('/static/home/done', express.static('static/home/done'));
// app.use(express.static('static/home/done'));

3. 修复前端图片路径问题

默认serve-index返回的a标签href是相对路径(比如test.jpg),直接拼接会导致图片路径错误,调整jQuery代码:

$.ajax({
    url: "/static/home/done/",
    success: function (data) {
        $(data).find("a").each(function() {
            const imgPath = $(this).attr("href");
            // 排除上级目录链接(../),只匹配图片文件
            if (imgPath.match(/\.(jpe?g|png|gif|JPG)$/) && !imgPath.startsWith('.')) {
                const fullSrc = "/static/home/done/" + imgPath;
                const slideHtml = `<div class='slide'><img src='${fullSrc}'></div>`;
                $("#done_work_1").append(slideHtml);
                $("#done_work_2").append(slideHtml);
            }
        });
    }
});

完成以上三步后,重启Node服务,访问页面就能正常加载static/home/done目录下的图片了。

内容的提问来源于stack exchange,提问作者hossein ghodrati

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 15:04:58