带有Express的NodeJS Electron [英] NodeJS Electron with express

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

问题描述

我正在尝试使用电子制作一个Web应用程序(用于网站和桌面应用程序)并进行表达(用于会话等)。

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 ,则会出现此错误:
    行: app .on('ready',onAppReady);

  1. If I use node app.js, I get this error: Line: app.on('ready', onAppReady);

TypeError:无法在对象上读取未定义
的属性 on。 (/home/josh/chat_program/client/app.js:26:4)Module._compile中的
(module.js:571:32)Object.Module._extensions..js中的
(模块.js:580:10)Module.load(module.js:488:32)
tryModuleLoad(module.js:447:12)
在Function.Module._load( module.js:439:3)Module.runMain的
(module.js:605:10)运行时的
(bootstrap_node.js:420:7)启动时的
(bootstrap_node.js :139:9)bootstrap_node.js:$ 535:3

TypeError: Cannot read property 'on' of undefined at Object. (/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

$ c>,应用程序启动,但是我没有收到请求或网页。我得到的只是基本的HTML,没有任何内容(只有doctype HTML HEAD和BODY)。

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).

我搜索了很长时间但找不到任何东西。

I searched for a long time but couldn't find anything.

推荐答案

两件事。

首先,请澄清您的路径设置和用法,例如:

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');

第二,我将所有快速代码包装到一个具有自我执行功能的文件中,因此它会在您需要时运行一次。例如我称为 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),我实例化应用程序和快递服务器,如下所示:

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.

这篇关于带有Express的NodeJS Electron的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆