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

Electron应用部署后Express路由连接失败(net::ERR_CONNECTION_REFUSED)

Electron打包后Express路由无法访问(net::ERR_CONNECTION_REFUSED)问题解决

开发模式下集成Express的Electron项目功能正常,但打包安装后API请求报错net::ERR_CONNECTION_REFUSED,可从以下几个方向排查解决:

1. 修正Express服务的路径引用

打包后Electron的__dirname指向asar包内路径,开发时的相对路径在生产环境会失效。需用Electron提供的app.getAppPath()获取正确的应用根路径:

// nodejs/server.js
const { app } = require('electron');
const express = require('express');
const path = require('path');
const server = express();

// 示例:设置静态资源路径
server.use(express.static(path.join(app.getAppPath(), 'front')));

// 示例:路由定义
server.get('/api/test', (req, res) => {
  res.json({ message: 'success' });
});

const port = process.env.PORT || 3000;
server.listen(port, () => {
  console.log(`Express server running on port ${port}`);
});

2. 确保打包时包含所有必要文件

检查electron-builder配置,确保Express服务相关文件(如nodejs/目录)被纳入打包范围。修改package.json的build字段:

{
  "build": {
    "extraResources": ["./extraResources/**"],
    "files": [
      "main.js",
      "preload.js",
      "nodejs/**",
      "front/**",
      "node_modules/**"
    ]
  }
}

若项目包含原生模块,需确保打包前执行npm run build:gyp完成对应平台的编译。

3. 调整Express服务启动时机

确保Express服务在Electron应用就绪后启动,避免前端页面加载时服务尚未就绪。修改main.js:

app.whenReady().then(() => {
  // 优先启动Express服务
  require('./nodejs/server');
  createWindow();

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

4. 修正前端API请求路径

前端避免硬编码localhost地址,改用相对路径或动态注入基础URL:

  • 方案一:使用相对路径请求API,如fetch('/api/test'),确保Express路由能直接处理。
  • 方案二:通过preload脚本注入环境配置:
    // preload.js
    const { contextBridge } = require('electron');
    contextBridge.exposeInMainWorld('appConfig', {
      apiBaseUrl: process.env.NODE_ENV === 'development' ? 'http://localhost:3000' : ''
    });
    
    前端请求时使用:fetch(${window.appConfig.apiBaseUrl}/api/test)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:30:52