[英]how to access global variables / or used port in front end, while running server by nodejs
I have我有
router.get('/',function(req,res){
res.sendFile('index.html', { root: __dirname });
//__dirname : It will resolve to your project folder.
});
calling index.html file.调用 index.html 文件。 It has script tag with script.它有带有脚本的脚本标签。
Calling of environmental variable in app.js file works well在 app.js 文件中调用环境变量效果很好
var port =process.env.port ||process.env.PORT || 3000;
but error starts if I run this in the script tag of index.html但是如果我在 index.html 的脚本标签中运行它,错误就会开始
How can I access PORT environmental variable in that script tag?如何访问该脚本标签中的 PORT 环境变量? Is there way to run separate index.js file (I used <script src="./index.js"/>
and有没有办法运行单独的 index.js 文件(我使用<script src="./index.js"/>
和
alert()
console.log("s")
in that file, but it did nothing)在那个文件中,但它什么也没做)
You can't access environment variables directly on the client-side ( index.html
), but you can inject them in response or expose them as API endpoint and call it later from client-side.您不能直接在客户端( index.html
)上访问环境变量,但您可以在响应中注入它们或将它们公开为 API 端点并稍后从客户端调用它。
Write port
to response and return as text/html
.将port
写入响应并以text/html
形式返回。
app.get('/', function(req, res) { return res.send(`Application listening at ${process.env.PORT || port}.`); });
Return port
as application/json
以application/json
的形式返回port
app.get('/', function(req, res) { return res.send({ port: process.env.PORT || port }) });
This in your html will give you the port used. html 中的这将为您提供使用的端口。
window.location.port
eg:例如:
<script>
var port = window.location.port;
alert(port);
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.