NodeJS Electron 与 express

2023-01-29前端开发问题
10

本文介绍了NodeJS Electron 与 express的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试使用电子(用于网站和桌面应用程序)和 express(用于会话等)制作网络应用程序

I'm trying to make a webapplication using electron (for the website and desktop application) and express (for sessions etc.)

现在,我把它作为我的 app.js:

Now, I got this as my app.js:

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

exp = express();
exp.set('views', __dirname + '/views/');
exp.use(express.static(process.cwd() + '/views'));
exp.get('/', function(req, res) {
    res.render('index', {});
});

function onAppReady() 
{
    mainWindow = new BrowserWindow({
        width: 1080,
        height: 720,
        autoHideMenuBar: true,
        useContentSize: true,
        resizable: false
    });

    mainWindow.loadURL('http://localhost:5000/');
    mainWindow.focus();
    mainWindow.webContents.openDevTools();
}

app.on('ready', onAppReady);

现在,有几个问题:

  1. 如果我使用 node app.js,我会收到此错误:
  1. If I use node app.js, I get this error:

Line: `app.on('ready', onAppReady);`

TypeError: Cannot read property 'on' of undefined
at Object.<anonymous> (/home/josh/chat_program/client/app.js:26:4)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3

  1. 如果我使用 electron .,应用程序会启动,但我没有收到请求或网页.我得到的只是基本的 HTML,没有任何东西(只有 doctype HTML HEAD 和 BODY).
  1. If I use electron ., the application starts, but I don't get either a request or a webpage. All I get is basic HTML without anything (only doctype HTML HEAD and BODY).

找了半天也没找到.

推荐答案

两件事.

首先我要澄清一下你的路径设置和使用,更像这样:

First I'd clarify your pathing setup and usage, more like this:

const publicPath = path.resolve(__dirname, '/views');
// point for static assets
app.use(express.static(publicPath));
//view engine setup
app.set('views', path.join(__dirname, '/views/'));

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

其次,我会将我所有的 express 代码包装到一个文件中,该文件是一个自执行函数,因此它会在您需要时运行一次.比如我的快递文件,我称之为 app.js 文件:

Second, I would wrap all my express code into a single file that is a self-executing function, so it runs once when you require it. Such as my express file which I call my app.js file:

'use strict';
(function () {
    const express = require('express');
    const path = require('path');
    const logger = require('morgan');
    const cookieParser = require('cookie-parser');
    const bodyParser = require('body-parser');
    const routes = require('./routes.js');

    const app = express();
    const publicPath = path.resolve(__dirname, '../dist');
    const port = 3000;

    // point for static assets
    app.use(express.static(publicPath));

    //view engine setup
    app.set('views', path.join(__dirname, '../dist'));
    app.engine('html', require('ejs').renderFile);
    app.set('view engine', 'html');

    app.use(logger('dev'));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
        extended:true
    }));

    app.use('/', routes);

    app.use(cookieParser());

    const server = app.listen(port, () => console.log(`Express server listening on port ${port}`));

    module.exports = app;

}());

然后在我的主文件(在我的例子中我称之为 main.js 而不是 app.js)中,我将应用程序和 express 服务器实例化如下:

Then in my main file (which I call main.js not app.js, in my case), I instantiate the app and the express server as follows:

'use strict';
const app = require('electron').app;
const Window = require('electron').BrowserWindow; // jshint ignore:line
const Tray = require('electron').Tray; // jshint ignore:line
const Menu = require('electron').Menu; // jshint ignore:line
const fs = require('fs');

const server = require('./ServerSide/app');

let mainWindow = null;

app.on('ready', function () { 
    const path = require('path');
    const iconPath = path.resolve(__dirname, './dist/myicon.ico');
    const appIcon = new Tray(iconPath);
    mainWindow = new Window({
        width: 1280,
        height: 1024,
        autoHideMenuBar: false,
        useContentSize: true,
        resizable: true,
        icon: iconPath
        //  'node-integration': false // otherwise various client-side things may break
    });
    appIcon.setToolTip('My Cool App');
    mainWindow.loadURL('http://localhost:3000/');

    // remove this for production
    var template = [
        {
            label: 'View',
            submenu: [
                {
                    label: 'Reload',
                    accelerator: 'CmdOrCtrl+R',
                    click: function(item, focusedWindow) {
                        if (focusedWindow) {
                            focusedWindow.reload();
                        }
                    }
                },
                {
                    label: 'Toggle Full Screen',
                    accelerator: (function() {
                        if (process.platform === 'darwin') {
                            return 'Ctrl+Command+F';
                        } else {
                            return 'F11';
                        }
                    })(),
                    click: function(item, focusedWindow) {
                        if (focusedWindow) {
                            focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
                        }
                    }
                },
                {
                    label: 'Toggle Developer Tools',
                    accelerator: (function() {
                        if (process.platform === 'darwin') {
                            return 'Alt+Command+I';
                        } else {
                            return 'Ctrl+Shift+I';
                        }
                    })(),
                    click: function(item, focusedWindow) {
                        if (focusedWindow) {
                            focusedWindow.toggleDevTools();
                        }
                    }
                }
            ]
        }
    ];

    const menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);

    mainWindow.focus();

});

// shut down all parts to app after windows all closed.
app.on('window-all-closed', function () {
    app.quit();
});

请注意,我在 Windows 平台上成功使用了此功能,因此可能需要对本示例中列出的任何平台特定项目进行小幅调整.

Note that I am using this with success on Windows platform, so small tweaks may be needed for any platform specific items listed in this example.

这篇关于NodeJS Electron 与 express的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

layui实现laydate日历控件控制之前日期不可选择
具体实现代码如下: laydate.render({ elem: '#start_time', min:0, //,type: 'date' //默认,可不填}); 只要加一个min参数,就可以控制了。0表示之前的日期不可...
2024-11-29 前端开发问题
133

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui laydate日期时间范围,时间默认设定为23:59:59
在Layui中,如果你想设置日期时间选择器(datetime)的默认结束时间为当天的23:59:59,你可以使用如下代码: laydate.render({ elem: '#test10' ,type: 'datetime' ,range: true ,max: '{:date("Y-m-d 23:59:59")}' ,ready: function(date){ $(".layui-laydat...
2024-10-24 前端开发问题
279

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

jQuery怎么动态向页面添加代码?
append() 方法在被选元素的结尾(仍然在内部)插入指定内容。 语法: $(selector).append( content ) var creatPrintList = function(data){ var innerHtml = ""; for(var i =0;i data.length;i++){ innerHtml +="li class='contentLi'"; innerHtml +="a href...
2024-10-18 前端开发问题
125

JavaScript(js)文件字符串中丢失"\"斜线的解决方法
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转...
2024-10-17 前端开发问题
437