简体   繁体   中英

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. It has script tag with script.

Calling of environmental variable in app.js file works well

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

but error starts if I run this in the script tag of index.html

How can I access PORT environmental variable in that script tag? Is there way to run separate index.js file (I used <script src="./index.js"/> and

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.

  1. Write port to response and return as text/html .

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

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

This in your html will give you the port used.

window.location.port

eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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