简体   繁体   English

在 NodeJs 中检索 Azure 环境变量

[英]Retrieve Azure environment variables in NodeJs

I have an app service set up in Azure with a static built NodeJS web application.我在 Azure 中设置了一个应用服务,其中包含一个静态构建的 NodeJS Web 应用程序。 The application runs fine and I want to move the api key and hostname of the api to variables in the environment.应用程序运行良好,我想将 api 的 api 密钥和主机名移动到环境中的变量中。

In Azure->Settings->Configuration->Application Settings I have added two environment variables and set a value for each.在 Azure->Settings->Configuration->Application Settings 中,我添加了两个环境变量并为每个变量设置了一个值。

In my Constants.js file I have在我的 Constants.js 文件中,我有

export const token = process.env.API_KEY;
export const host = process.env.API_HOST;

But process.env.API_KEY is always null.但 process.env.API_KEY 始终为空。

I have even tried :我什至尝试过:

export const token = process.env["API_KEY"];

To no avail.无济于事。 What am I doing wrong?我究竟做错了什么?

Both of the code you provided all work on my side.你提供的两个代码都在我这边工作。

export const token = process.env.API_KEY;
export const token = process.env["API_KEY"];

Try to redeploy your website and view it in another browser.尝试重新部署您的网站并在另一个浏览器中查看它。

在此处输入图片说明

Update:更新:

const http = require('http');

//var APPINSIGHTS_INSTRUMENTATIONKEY= process.env.APPINSIGHTS_INSTRUMENTATIONKEY;

const server = http.createServer((request, response) => {
    var a,b,c;
    if(process.env.NODE_ENV === "production")
    {
        a= process.env.NODE_ENV ;
        b= process.env.APPINSIGHTS_INSTRUMENTATIONKEY;
        c= process.env.KEY_VALUE;
    }
    else if(process.env.NODE_ENV === "development")
    {
        a="Welcome";
        b="testparams";
        c="testvalue";
    }
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.end(a+"  && "+b+"myCustomKey="+c);
});

const port = process.env.PORT || 1337;
server.listen(port);

console.log("Server running at http://localhost:%d", port);

I ran into this same issue and had the same env vars (mentioned in a follow up answer by the author) showing then finally found that the scripts used by create-react-app specifically expose those vars plus any beginning with REACT_APP_ .我遇到了同样的问题,并且有相同的 env vars(在作者的后续回答中提到)显示然后最终发现 create-react-app 使用的脚本专门公开这些 vars 以及任何以REACT_APP_开头的REACT_APP_

I tweaked the logic to allow for additional env vars to pass through, or you could rename you're variables to use the above prefix.我调整了逻辑以允许通过其他环境变量,或者您可以重命名变量以使用上述前缀。

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

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