简体   繁体   中英

Serve static files with express from within electron-forge app

I've written a quick Electron Forge app that simply runs an express webserver that serves static files locally. I prefer this to running a node process directly for usability.

main.js

import { app, BrowserWindow } from 'electron';
import express from 'express';

const exApp = express();
exApp.use(express.static('web-app'));
exApp.listen(3333);

let mainWindow;

const createWindow = () => {
  // Create the browser window.
  mainWindow = new BrowserWindow({
  // ...
  });

  // ...
};

// ...

I use the CopyWebpackPlugin to copy the files I need to serve into the .webpack/main/web-app/ directory.

webpack.main.config.js

module.exports = {
  /**
   * This is the main entry point for your application, it's the first file
   * that runs in the main process.
   */
  entry: './src/main.js',
  // Put your normal webpack config below here
  module: {
    rules: require('./webpack.rules'),
  },
  plugins: [
    new CopyPlugin([
      { from: path.resolve(__dirname, 'web-app'), to: 'web-app' }
    ]),
  ]
};

This works perfectly in development (via yarn start ).

When I try to run yarn make , it successfully builds the app and generates a runnable exe, but trying to access http://localhost:3333/ after running the app, results in a Cannot GET / 404 message.

Any idea what I'm doing wrong?

What I was serving in development was actually the web-app directory relative to the node process, and not the one copied into .webpack/... .

To serve the proper files in production, I changed the exApp.use() line to:

exApp.use(express.static('resources/app/.webpack/main/web-app'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM