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

如何在Express下发脚本中读取Electron本地JSON并上传至服务器

解决方案:Electron 读取本地 JSON 并上传至 Express 服务器

下面分Electron 端(读取本地文件+上传)和Express 端(接收数据)两部分给出具体实现:


Electron 端实现

1. 配置主进程(main.js)

要在渲染进程使用 Node.js 文件系统模块,需调整窗口的 webPreferences 配置。开发环境可直接开启 Node 集成,生产环境建议用 preload 脚本(更安全):

开发环境配置

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

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });
  mainWindow.loadFile('index.html');
}

app.whenReady().then(createWindow);
app.on('window-all-closed', () => process.platform !== 'darwin' && app.quit());
app.on('activate', () => BrowserWindow.getAllWindows().length === 0 && createWindow());

生产环境安全配置(preload 脚本)

创建 preload.js,仅暴露必要的文件读取 API:

const { contextBridge, ipcRenderer } = require('electron');
const fs = require('fs').promises;
const { app } = require('electron');
const path = require('path');

contextBridge.exposeInMainWorld('electronAPI', {
  readLocalJSON: async (fileName) => {
    const safePath = path.join(app.getPath('userData'), fileName);
    const rawData = await fs.readFile(safePath, 'utf8');
    return JSON.parse(rawData);
  }
});

然后修改 main.js 中的 webPreferences:

webPreferences: {
  preload: path.join(__dirname, 'preload.js'),
  contextIsolation: true // 保持开启,默认值
}

2. 渲染进程读取并上传数据

在 index.html 中编写交互逻辑:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>上传JSON</title>
</head>
<body>
  <button id="uploadBtn">上传本地数据</button>
  <script>
    const uploadBtn = document.getElementById('uploadBtn');
    
    uploadBtn.addEventListener('click', async () => {
      try {
        // 方式1:开发环境直接用fs
        // const fs = require('fs').promises;
        // const path = require('path');
        // const filePath = path.join(require('electron').app.getPath('userData'), 'data.json');
        // const parsedData = JSON.parse(await fs.readFile(filePath, 'utf8'));

        // 方式2:生产环境用preload脚本
        const parsedData = await window.electronAPI.readLocalJSON('data.json');

        // 发送到Express服务器
        const res = await fetch('http://localhost:3000/upload', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(parsedData)
        });

        if (res.ok) {
          const result = await res.json();
          alert(`上传成功:${result.message}`);
        } else {
          throw new Error('服务器响应异常');
        }
      } catch (err) {
        console.error('操作失败:', err);
        alert(`操作失败:${err.message}`);
      }
    });
  </script>
</body>
</html>

Express 端实现

1. 初始化项目并安装依赖

mkdir express-upload && cd express-upload
npm init -y
npm install express cors

2. 编写服务器代码(server.js)

const express = require('express');
const cors = require('cors');
const app = express();
const PORT = 3000;

// 允许跨域请求(Electron本地请求属于跨域)
app.use(cors());
// 解析JSON格式的请求体
app.use(express.json());

// 处理上传请求的接口
app.post('/upload', (req, res) => {
  const uploadedData = req.body;
  
  // 这里可根据需求处理数据:保存到数据库、写入本地文件等
  console.log('收到上传数据:', uploadedData);
  
  // 返回响应
  res.json({
    success: true,
    message: '数据接收成功',
    receivedData: uploadedData
  });
});

app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});

3. 启动服务器

node server.js

关键注意事项

  • 权限问题:Electron 读取文件时,优先使用 app.getPath('userData')、app.getPath('documents') 等系统提供的安全路径,避免读取敏感目录导致权限被拒。
  • 生产环境安全:禁止在生产环境开启 nodeIntegration: true 和 contextIsolation: false,必须用 preload 脚本暴露最小必要 API,防止 XSS 风险。
  • 跨域配置:Express 必须启用 cors 中间件,否则 Electron 的请求会被浏览器同源策略拦截。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 12:15:32