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

react-router-dom配合Express+webpack中间件自定义开发服路由404求解

问题原因

webpack-dev-middleware 默认会将所有编译产物(包括 HtmlWebpackPlugin 生成的 index.html)存储在内存中,不会写入本地磁盘。你当前通配路由中使用 Node 原生 fs 模块读取磁盘路径下的 index.html,自然找不到对应文件返回404,只有开启 writeToDisk 配置后产物被写入磁盘,才能正常读取文件。

解决方案

修改 server.js 中的通配路由逻辑,改用 webpack 编译实例暴露的内存文件系统 API 读取产物即可,无需写入磁盘:

// 替换你原有的 app.get('*') 代码
app.get('*', (req, res, next) => {
  const indexHtmlPath = path.join(compiler.outputPath, 'index.html');
  // 从内存文件系统读取index.html
  compiler.outputFileSystem.readFile(indexHtmlPath, (err, fileContent) => {
    if (err) {
      return next(err);
    }
    res.setHeader('Content-Type', 'text/html');
    res.send(fileContent);
    res.end();
  });
});

修改完成后重启开发服务,即可在不开启 writeToDisk 的前提下正常访问所有路由。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 01:27:01