You need to enable JavaScript to run this app. Electron React应用打包后访问非默认路由及登录报net::ERR_FILE_NOT_FOUND
优惠活动
大模型
产品
解决方案
定价
更多

Electron React应用打包后访问非默认路由及登录报net::ERR_FILE_NOT_FOUND

问题现象
  • 经electron-packager打包后的应用运行时,加载默认路由正常,访问其他任意路由都会抛出net::ERR_FILE_NOT_FOUND错误
  • 登录页点击登录按钮发起请求时,控制台抛出POST file:///logIn net::ERR_FILE_NOT_FOUND报错

相关配置代码

Electron主进程配置

const electron = require('electron');
const { app, BrowserWindow } = electron;
const path = require('path');
const isDev = require('electron-is-dev');
const url = require('url');

let mainWindow = null;
const createWindow = () => {
    mainWindow = new BrowserWindow({
        width: 1024, height: 1024,
        autoHideMenuBar: true,
        useContentSize: true,
        resizable: true,
        webPreferences: {
            nodeIntegration: true,
            devTools: true
        }

    })


    mainWindow.loadURL(`file://${__dirname}/../build/index.html#/`);

    mainWindow.on('closed', () => mainWindow = null)

    mainWindow.webContents.openDevTools();


}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') { app.quit() }
})

app.on('activate', () => {
    if (mainWindow === null) { createWindow() }
})

package.json 相关配置

"main": "public/electron.js",
"homepage": "./",
"name": "security-tool",
"version": "0.1.0",
"private": true,
"build": {
  "appId": "",
  "extends": null,
  "files": [
    "node_modules/**/*",
    "package.json",
    "electron.js",
    "build/**/*"
  ],
  "directories": {
    "buildResources": "assets"
  }
},

React端路由配置

ReactDOM.render(
  <CookiesProvider>
    <HashRouter>
      <Switch>
        <Route path="/home" component={Home} />
        <Route path="/projects" component={Projects} />
        <Route path="/settings" component={Settings} />
        <Route path="/form" component={Form} />
        <Route exact path="/" component={Login} />
      </Switch>
    </HashRouter>
  </CookiesProvider>,
  document.getElementById('root')
);

登录逻辑代码片段

logIn = async() => {
  let results = await logInEndpoint(this.state.Username, this.state.Password);
      if(results.result === "Success!") {
        const { cookies } = this.props;
 
        cookies.set('userID', results.data[0].USER_ID, { path: '/', maxAge: 3600 });

        this.props.history.push('/home');
      }
      else{
        this.invalidCreds(results.result);
      }
}

核心问题诱因

  • 路由报错:Electron 通过file://协议加载本地静态资源时,没有服务端的路径重写能力;路由跳转时如果路径没有正确落在hash锚点范围内,浏览器会将跳转路径解析为本地磁盘文件路径发起请求,匹配不到对应文件就会触发ERR_FILE_NOT_FOUND
  • 登录请求报错:登录接口使用了根相对路径/logIn,在file://协议环境下,这类相对路径会被直接解析为磁盘根目录下的本地文件路径,而非后端服务接口地址,因此会抛出文件不存在的错误

内容的提问来源于stack exchange,提问作者jylin-arch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.04 23:06:07