【问题标题】:electron js - serving html电子 js - 服务 html
【发布时间】:2022-02-02 01:46:12
【问题描述】:

我正在尝试提供另一个 html 文件,以便浏览器可以从 electronjs 访问它。这是文件目录:

app folder:
- index.js // this is the init file for electron.
- index.html // main interface.
- ip.js // <-- included in index.html, codes for serving the static html to browser.
- package.json
-- node_modules
-- pad: // <-- this is the root folder I want to access via browser
    - index.html // <-- browser will get to see this page.
    - pad_index.js

index.js 将有基本的electron js 东西。 'index.html' 将导入并运行ip.js,其中包含将./pad/index.html 提供给浏览器的代码。

ip.js:
var os = require("os");

const http = require("http");
var path = require("path");
var url = require("url");
var fs = require("fs");

const port = 3000;

var staticBasePath = "./pad/";

var staticServe = function(req, res) {
  var resolvedBase = path.resolve(staticBasePath);
  var safeSuffix = path.normalize(req.url).replace(/^(\.\.[\/\\])+/, "");
  var fileLoc = path.join(resolvedBase, safeSuffix);

  var stream = fs.createReadStream(fileLoc);

  stream.on("error", function(error) {
    res.writeHead(404, "Not Found");
    res.write("404: File Not Found!");
    res.end();
  });
  res.statusCode = 200;
  stream.pipe(res);
};

var httpServer = http.createServer(staticServe);

httpServer.listen(port,  () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

当我使用electron . 对其进行测试时,一切正常。我可以去浏览器输入http://localhost:3000/index.html,它会显示来自./pad/index.html的内容。

但是在我使用electron builder 构建应用程序,然后运行构建的应用程序后,我在浏览器中得到404: file not found!。我确信我错过了一些非常重要的东西,但不确定是什么。

我该如何解决这个问题?

【问题讨论】:

    标签: javascript electron


    【解决方案1】:

    根据电子生成器配置,您必须更改 directories 部分以允许您的文件与应用程序一起打包。

    查看directories 部分:https://www.electron.build/configuration/configuration#configuration

    这个答案可能会有所帮助 Electron index.html not loading after building the app

    【讨论】:

    • 感谢您的指点,但我不确定这是否是我要找的。注意我有 2 个index.html?那些有不同的内容。我可以看到root/indext.html 很好,只是无法访问我在root/pad/index.html 中的localhost:3000/index.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多