[英]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 端點並稍后從客戶端調用它。
將port
寫入響應並以text/html
形式返回。
app.get('/', function(req, res) { return res.send(`Application listening at ${process.env.PORT || port}.`); });
以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.