我创建了我的React应用程序的构建,并与Electron.js连接。现在如何将我的后端从服务器文件夹与电子连接

发布于 2025-01-30 18:02:37 字数 984 浏览 2 评论 0原文

我创建了我的React应用程序的构建,并与Electron.js连接。现在如何将我的后端从服务器文件夹与电子连接。

如何将后端添加到Electron .exe。

const { app, BrowserWindow } = require('electron')
const path = require('path')
require('./app');
                
function createWindow() {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        }
    })
                
    // win.loadFile('./demo.html')
    win.loadFile('./build/index.html')
}
                
app.whenReady().then(() => {
    createWindow()
    
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow()
        }
    })
})
                
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

这是我的文件夹结构

I create a build of my react app and connected with electron.js. now how to connect my backend from server folder with electron.

How can I add backend to electron .exe

const { app, BrowserWindow } = require('electron')
const path = require('path')
require('./app');
                
function createWindow() {
    const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        }
    })
                
    // win.loadFile('./demo.html')
    win.loadFile('./build/index.html')
}
                
app.whenReady().then(() => {
    createWindow()
    
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow()
        }
    })
})
                
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

This is my folder structure

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情域 2025-02-06 18:02:37

首先在前端文件中检查您的路由(例如React中的index.js),如果它是browserrouter,则将其更改为Hashrouter。
现在复制以下代码并将其粘贴到电子主文件

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

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // win.loadFile('./demo.html')
  win.loadURL('http://localhost:9000')
  win.loadURL('./build/index.html')
}

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

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

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


// ******************************************************************************


/* const electron = require('electron')
const app = electron.app
handleSquirrelEvent(app)
const BrowserWindow = electron.BrowserWindow;
const path = require('path')
// const url = require('electron-is-dev');
const isDev = require('electron-is-dev');
let mainWindow;
// const createWindow = () => {
//     mainWindow = new BrowserWindow({ width: 800, height: 600 })
//     const appUrl = isDev ? 'http://localhost:3000' :
//         `file://${path.join(__dirname, '../build/index.html')}`
//     mainWindow.loadURL(appUrl)
//     // mainWindow.loadURL(url.format({
//     //     pathname: path.join(__dirname, '../build/index.html'),
//     //     protocol: 'file',
//     //     slashes: true
//     // }))
//     mainWindow.webContents.openDevTools()
//     mainWindow.on('closed', function () {
//         mainWindow = null
//     })
// }
// app.on('ready', createWindow)
// app.on('window-all-closed', function () {
//     if (process.platform !== 'darwin') {
//         app.quit()
//     }
// })
// app.on('activate', function () {
//     if (mainWindow === null) {
//         createWindow()
//     }
// })
const createWindow = () => {
  mainWindow = new BrowserWindow({ width: 480, height: 320 })
  const appUrl = isDev ? 'http://localhost:3000' :
    `file://${path.join(__dirname, '../build/index.html')}`
  mainWindow.loadURL(appUrl)
  mainWindow.maximize()
  mainWindow.setFullScreen(true)
  mainWindow.on('closed', () => mainWindow = null)
}
app.on('ready', createWindow)
app.on('window-all-closed', () => {
  // Follow OS convention on whether to quit app when
  // all windows are closed.
  if (process.platform !== 'darwin') { app.quit() }
})
app.on('activate', () => {
  // If the app is still open, but no windows are open,
  // create one when the app comes into focus.
  if (mainWindow === null) { createWindow() }
})
function handleSquirrelEvent(application) {
  if (process.argv.length === 1) {
    return false;
  }
  const ChildProcess = require('child_process');
  const path = require('path');
  const appFolder = path.resolve(process.execPath, '..');
  const rootAtomFolder = path.resolve(appFolder, '..');
  const updateDotExe = path.resolve(path.join(rootAtomFolder, 'Update.exe'));
  const exeName = path.basename(process.execPath);
  const spawn = function (command, args) {
    let spawnedProcess, error;
    try {
      spawnedProcess = ChildProcess.spawn(command, args, {
        detached: true
      });
    } catch (error) { }
    return spawnedProcess;
  };
  const spawnUpdate = function (args) {
    return spawn(updateDotExe, args);
  };
  const squirrelEvent = process.argv[1];
  switch (squirrelEvent) {
    // case '--squirrel-install': 58
    case '--squirrel-updated':
      // Optionally do things such as:
      // - Add your .exe to the PATH
      // - Write to the registry for things like file associations and
      //   explorer context menus
      // Install desktop and start menu shortcuts
      spawnUpdate(['--createShortcut', exeName]);
      setTimeout(application.quit, 1000);
      return true;
    case '--squirrel-uninstall':
      // Undo anything you did in the --squirrel-install and
      // --squirrel-updated handlers
      // Remove desktop and start menu shortcuts
      spawnUpdate(['--removeShortcut', exeName]);
      setTimeout(application.quit, 1000);
      return true;
    case '--squirrel-obsolete':
      // This is called on the outgoing version of your app before
      // we update to the new version - it's the opposite of
      // --squirrel-updated
      application.quit();
      return true;
    default:
      console.log("default case")
  }
};

 */

// ******************************************************************************

/* const electron = require('electron')
const path = require("path");
const url = require('url');
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow


process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({ width: 800, height: 600 })

  // and load the index.html of the app.
  // 'public' is the path where webpack bundles my app
  mainWindow.loadURL(`file://${__dirname}/public/index.html`);

  // Open the DevTools.
  mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
}) */`enter code here`

Check your routing first in the frontend file (like an index.js in react) if it is BrowserRouter then change it to HashRouter.
Now copy the below code and paste it to the electron main file

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

function createWindow() {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // win.loadFile('./demo.html')
  win.loadURL('http://localhost:9000')
  win.loadURL('./build/index.html')
}

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

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

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


// ******************************************************************************


/* const electron = require('electron')
const app = electron.app
handleSquirrelEvent(app)
const BrowserWindow = electron.BrowserWindow;
const path = require('path')
// const url = require('electron-is-dev');
const isDev = require('electron-is-dev');
let mainWindow;
// const createWindow = () => {
//     mainWindow = new BrowserWindow({ width: 800, height: 600 })
//     const appUrl = isDev ? 'http://localhost:3000' :
//         `file://${path.join(__dirname, '../build/index.html')}`
//     mainWindow.loadURL(appUrl)
//     // mainWindow.loadURL(url.format({
//     //     pathname: path.join(__dirname, '../build/index.html'),
//     //     protocol: 'file',
//     //     slashes: true
//     // }))
//     mainWindow.webContents.openDevTools()
//     mainWindow.on('closed', function () {
//         mainWindow = null
//     })
// }
// app.on('ready', createWindow)
// app.on('window-all-closed', function () {
//     if (process.platform !== 'darwin') {
//         app.quit()
//     }
// })
// app.on('activate', function () {
//     if (mainWindow === null) {
//         createWindow()
//     }
// })
const createWindow = () => {
  mainWindow = new BrowserWindow({ width: 480, height: 320 })
  const appUrl = isDev ? 'http://localhost:3000' :
    `file://${path.join(__dirname, '../build/index.html')}`
  mainWindow.loadURL(appUrl)
  mainWindow.maximize()
  mainWindow.setFullScreen(true)
  mainWindow.on('closed', () => mainWindow = null)
}
app.on('ready', createWindow)
app.on('window-all-closed', () => {
  // Follow OS convention on whether to quit app when
  // all windows are closed.
  if (process.platform !== 'darwin') { app.quit() }
})
app.on('activate', () => {
  // If the app is still open, but no windows are open,
  // create one when the app comes into focus.
  if (mainWindow === null) { createWindow() }
})
function handleSquirrelEvent(application) {
  if (process.argv.length === 1) {
    return false;
  }
  const ChildProcess = require('child_process');
  const path = require('path');
  const appFolder = path.resolve(process.execPath, '..');
  const rootAtomFolder = path.resolve(appFolder, '..');
  const updateDotExe = path.resolve(path.join(rootAtomFolder, 'Update.exe'));
  const exeName = path.basename(process.execPath);
  const spawn = function (command, args) {
    let spawnedProcess, error;
    try {
      spawnedProcess = ChildProcess.spawn(command, args, {
        detached: true
      });
    } catch (error) { }
    return spawnedProcess;
  };
  const spawnUpdate = function (args) {
    return spawn(updateDotExe, args);
  };
  const squirrelEvent = process.argv[1];
  switch (squirrelEvent) {
    // case '--squirrel-install': 58
    case '--squirrel-updated':
      // Optionally do things such as:
      // - Add your .exe to the PATH
      // - Write to the registry for things like file associations and
      //   explorer context menus
      // Install desktop and start menu shortcuts
      spawnUpdate(['--createShortcut', exeName]);
      setTimeout(application.quit, 1000);
      return true;
    case '--squirrel-uninstall':
      // Undo anything you did in the --squirrel-install and
      // --squirrel-updated handlers
      // Remove desktop and start menu shortcuts
      spawnUpdate(['--removeShortcut', exeName]);
      setTimeout(application.quit, 1000);
      return true;
    case '--squirrel-obsolete':
      // This is called on the outgoing version of your app before
      // we update to the new version - it's the opposite of
      // --squirrel-updated
      application.quit();
      return true;
    default:
      console.log("default case")
  }
};

 */

// ******************************************************************************

/* const electron = require('electron')
const path = require("path");
const url = require('url');
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow


process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({ width: 800, height: 600 })

  // and load the index.html of the app.
  // 'public' is the path where webpack bundles my app
  mainWindow.loadURL(`file://${__dirname}/public/index.html`);

  // Open the DevTools.
  mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
}) */`enter code here`
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文