【发布时间】: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