【问题标题】:NodeJS Electron with expressNodeJS Electron 与 express
【发布时间】:2017-04-30 22:02:51
【问题描述】:

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

现在,我把它作为我的 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,我会收到此错误:
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)。

找了半天也没找到。

【问题讨论】:

  • 您需要将后端和前端部分分开
  • mmh 你的例子在这里没有问题......(电子。)
  • 是的,它可以工作,但它没有给我一个请求。

标签: javascript node.js express electron


【解决方案1】:

两件事。

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

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 文件:

'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 服务器实例化如下:

'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 平台上成功使用了此功能,因此可能需要对本示例中列出的任何平台特定项目进行小幅调整。

【讨论】:

  • 是的,我需要这个结构应用,并且快递应用用的是SQLite,但是,我的快递应用很大,所以,加载时间是5秒,我可以在加载时显示loading动画吗快递?
  • 你是如何运行这个应用程序的? 1. 使用节点 main.js 2. 电子 . ??
  • 不记得了,已经很久了,不过用electron main.js启动这个东西
猜你喜欢
  • 2020-08-16
  • 2014-11-14
  • 1970-01-01
  • 1970-01-01
  • 2020-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-05
相关资源
最近更新 更多