繁体   English   中英

nodejs运行服务器时如何在前端访问全局变量/或使用的端口

[英]how to access global variables / or used port in front end, while running server by nodejs

我有

router.get('/',function(req,res){
  res.sendFile('index.html', { root: __dirname });
  //__dirname : It will resolve to your project folder.
});

调用 index.html 文件。 它有带有脚本的脚本标签。

在 app.js 文件中调用环境变量效果很好

var port =process.env.port ||process.env.PORT || 3000;

但是如果我在 index.html 的脚本标签中运行它,错误就会开始

如何访问该脚本标签中的 PORT 环境变量? 有没有办法运行单独的 index.js 文件(我使用<script src="./index.js"/>

alert()
console.log("s")

在那个文件中,但它什么也没做)

您不能直接在客户端( index.html )上访问环境变量,但您可以在响应中注入它们或将它们公开为 API 端点并稍后从客户端调用它。

  1. port写入响应并以text/html形式返回。

     app.get('/', function(req, res) { return res.send(`Application listening at ${process.env.PORT || port}.`); });
  2. application/json的形式返回port

     app.get('/', function(req, res) { return res.send({ port: process.env.PORT || port }) });

html 中的这将为您提供使用的端口。

window.location.port

例如:

<script>
 var port = window.location.port;
 alert(port);
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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