【发布时间】:2020-02-26 23:31:35
【问题描述】:
我正在构建一个 electron/nodejs/react 应用程序,它将在用户本地主机上运行(例如 localhost:8080)。
我正在使用Portfinder 定位一个空闲端口并在该端口上运行应用程序。
portfinder
.getPortPromise()
.then(port => {
app.listen(port, function() {
console.log("Server started on localhost:" + port + ", Node ENV " + app.get("env"));
});
})
.catch(err => {
//Could not get a free port, `err` contains the reason.
});
在 React 应用程序中,我需要访问此端口号以将 http 请求发送回节点服务器。
除了在package.json 或.env 文件中使用环境变量之外,有没有办法在 React 或 Webpack 中访问这个动态创建的端口号?
【问题讨论】:
-
虽然这可能不是最佳解决方案 - 从安全角度来看 - 您可能希望将新端口号从后端保存在 cookie 中,然后在前端获取它。
标签: node.js reactjs express webpack electron