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

Angular17+Electron28视图重载后出现ERR_FILE_NOT_FOUND错误求助

Angular 17 + Electron 28 重载页面报错 ERR_FILE_NOT_FOUND 的解决方法

问题根源

初始加载时Electron直接指向index.html文件,因此能正常渲染;但点击重载后,Angular路由会将URL修正为目录路径(如file:///.../browser/),而Electron的file协议默认不会自动将目录路径解析为index.html,导致路径缺失文件名引发错误。

具体解决方法

方法一:动态设置Angular的base href

修改项目根目录下的index.html,替换静态base标签为动态生成的绝对路径,确保路由和重载时路径指向正确:

<script>
  // 自动获取index.html所在目录的绝对路径作为base href
  const basePath = window.location.pathname.replace(/index\.html$/, '');
  document.write(`<base href="${basePath}" />`);
</script>
<!-- 注释掉原静态base标签 -->
<!-- <base href="./" /> -->

方法二:拦截Electron导航请求,自动补全index.html

在Electron的窗口创建代码中添加导航拦截逻辑,当检测到请求目录路径时,自动追加index.html:

const { app, BrowserWindow } = require('electron');
const path = require('path');

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true
    }
  });

  win.loadFile(path.join(__dirname, "/dist/angular-electron/browser/index.html"));

  // 添加导航拦截
  win.webContents.on('will-navigate', (event, url) => {
    if (url.endsWith('/') && !url.includes('index.html')) {
      event.preventDefault();
      win.loadURL(`${url}index.html`);
    }
  });
}

app.whenReady().then(() => {
  createWindow();
});

方法三:确认Angular构建配置的baseHref正确

打开项目的angular.json,检查build配置中的baseHref是否设为./,确保构建后的资源路径适配本地文件加载:

"projects": {
  "angular-electron": {
    "architect": {
      "build": {
        "options": {
          "baseHref": "./",
          // ...其他构建配置
        }
      }
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 22:03:22