【问题标题】:Creating an Electron Application with Node.js Logic使用 Node.js 逻辑创建电子应用程序
【发布时间】:2018-07-26 22:08:24
【问题描述】:

我已经练习使用 Electron 几个月了,我想知道如何将我不久前制作的 Node.js 网页项目转换为 Electron 应用程序。在我的 Node.js 网页中,我使用了类似

的函数
app.get('/' function(req, res){
    res.render('loginpage');
}
app.post('/loginCredentials', function(req, res){
    /*Make sure req.body.username and req.body.password are valid*/
    res.render('home');
}

同样在我的 Node.js 应用程序中,每当用户想要查看数据库结果时,我都会在 Node.js 网页中查询数据库,并在呈现变量时将其发送到网页。

但是在 Electron 中,我不知道如何处理这样的请求。如果我想做一个 Electron 应用程序,我是否必须在网页文件中自己处理所有这些,或者 Electron 是否有一些 app.get/ app.post 方法?

或者,有没有办法让我的 Node.js 网页像 Electron 应用程序一样加载到浏览器窗口中?

提前谢谢你

更新 1; ipcMain模块功能:

在我的电子 main.js 文件中,我有以下代码:

const {ipcMain} = require('electron')
ipcMain.on('hello', (event, arg) => {
    console.log(arg)
    event.returnValue = 'pong'
})

在我的网页中,位于“./views”目录中,我有以下代码:(它是一个 pug 文件,它可以正确呈现)

input(type ='submit', value ='Submit', onclick = "handleClick()")
...
script.  
    const {ipcRenderer} = require('electron')
    function handleClick(){    
        var x = ipcRenderer.sendSync('hello', 'ping')
        console.log(x) 
    }

在进行以下更改之前,我一直收到错误消息(显示在问题的底部)。我改变了:

const ipcMain = require('electron') 

const {ipcMain} = require('electron')

显然,要正确导入模块,括号必须围绕模块。

存在但已修复的错误:

Uncaught TypeError: ipcRenderer.sendSync is not a function
    at handleClick (loginpage.pug:64)
    at HTMLInputElement.onclick 

ipcMain 是 Electron 中一个有用的方面,它模仿 Node.js 中的 app.get/app.post

【问题讨论】:

    标签: javascript jquery node.js get electron


    【解决方案1】:

    虽然在技术上可以将 Node.js 作为 Electron 应用程序的后端,但这将是一个笨拙的解决方案,不推荐使用。

    Electron 的 EventEmitter 类的实例通常用于前端和后端之间的通信,而不是 post/get 请求。使用后端的ipcMain 模块和前端的ipcRenderer 交换任何类型的数据。事实上,消息既可以同步发送,也可以异步发送。

    例如来自 Electron 的documentation

    // In main process.
    const {ipcMain} = require('electron')
    ipcMain.on('asynchronous-message', (event, arg) => {
      console.log(arg)  // prints "ping"
      event.sender.send('asynchronous-reply', 'pong')
    })
    
    ipcMain.on('synchronous-message', (event, arg) => {
      console.log(arg)  // prints "ping"
      event.returnValue = 'pong'
    })
    
    // In renderer process (web page).
    const {ipcRenderer} = require('electron')
    console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong"
    
    ipcRenderer.on('asynchronous-reply', (event, arg) => {
      console.log(arg) // prints "pong"
    })
    ipcRenderer.send('asynchronous-message', 'ping')
    

    【讨论】:

    • 我试过这个方法,但我一直收到错误。我将详细信息放在问题中的更新 1 下
    • 对于 Electron 应用程序,几乎所有内容都应该进入渲染器。你的“后端”代码不应该在主进程中,因为不仅是错误的方法,而且你有所有这些 IPC 问题......
    • @Tim 我有一个 ipcMain 问题,由于我犯了一个小错误(我需要模块周围的括号来导入),该问题已得到修复。您能否详细说明为什么 ipcMain 是错误的方法?
    • IPC 没有问题。然而,Electron 主进程不应该用于托管后端。几乎所有代码都应该在渲染器中
    猜你喜欢
    • 1970-01-01
    • 2022-06-14
    • 2015-11-10
    • 2021-09-14
    • 2016-04-24
    • 1970-01-01
    • 2021-04-07
    • 2021-09-20
    • 1970-01-01
    相关资源
    最近更新 更多