简体   繁体   English

在 Node.js 中使用 API 密钥的最佳实践

[英]Best practice when using an API key in Node.js

I have an API key I'm using in my Node.js application.我在 Node.js 应用程序中使用了一个 API 密钥。 Currently, I keep it stored in a text file and put it in a global variable when my application starts up.目前,我将它存储在一个文本文件中,并在我的应用程序启动时将它放在一个全局变量中。

So basically it's just:所以基本上它只是:

var key = getKey();
useKeyGetData(key);

I don't like having this global variable, and it's a pain to pass between files.我不喜欢有这个全局变量,而且在文件之间传递很痛苦。 Is there a better way to get my key where/when I need it?有没有更好的方法可以在我需要的地方/时间拿到我的钥匙? Is there some standard for doing so?这样做有什么标准吗?

The conventional alternative to what you're doing, especially when pertaining to API keys, is to use environment variables .您正在做的事情的传统替代方法,尤其是在与 API 密钥相关时,是使用环境变量 This is an operating system-level configuration facility.这是一个操作系统级别的配置工具。 Each process has its own set of environment variables, usually inherited from its parent process.每个进程都有自己的一组环境变量,通常从其父进程继承。 By convention, environment variables have uppercase names.按照惯例,环境变量具有大写名称。

In node.js, you can access environment variables through process.env .在 node.js 中,您可以通过process.env访问环境变量。 For example, if you run an application like this:例如,如果您运行这样的应用程序:

$ MY_VARIABLE=test node app.js

You can access the value of the MY_VARIABLE environment variable via:您可以通过以下方式访问MY_VARIABLE环境变量的值:

process.env.MY_VARIABLE

It can be tedious, however, to have to keep passing the environment variable(s) on each invocation of your program.但是,每次调用程序时都必须不断传递环境变量,这可能很乏味。 That's why there are packages such as dotenv which allow you to store your environment variables in a text file.这就是为什么有诸如dotenv 之类的软件包允许您将环境变量存储在文本文件中。

More specifically, you will have a file called .env and in it you might have:更具体地说,您将拥有一个名为.env的文件,其中可能包含:

MY_VARIABLE=test
OTHER_VARIABLE=foo

At the beginning of your app.js , you then do:app.js的开头,您执行以下操作:

require('dotenv').config();

This reads the environment variable values from the .env file.这会从.env文件中读取环境变量值。 You can then access them as you would access any other environment variables:然后,您可以像访问任何其他环境变量一样访问它们:

console.log("MY_VARIABLE: " + process.env.MY_VARIABLE);
console.log("OTHER_VARIABLE: " + process.env.OTHER_VARIABLE);

Now you don't have to explicitly pass the environment variables to your application upon invocation, ie you can just run it as usual:现在您不必在调用时显式地将环境变量传递给您的应用程序,即您可以像往常一样运行它:

$ node app.js

If you do pass one explicitly, it will override whatever value you gave in your .env file:如果明确地传递一个,它将覆盖你在给了任何价值.env文件:

$ MY_VARIABLE=bar node app.js

Now the MY_VARIABLE environment variable will have a value of "bar" instead of "testing" .现在MY_VARIABLE环境变量的值为"bar"而不是"testing" Since OTHER_VARIABLE isn't passed explicitly, it retains its value of "foo" specified in the .env file.由于OTHER_VARIABLE未显式传递,因此它保留其在.env文件中指定的"foo"值。

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

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