简体   繁体   English

NodeJS dotenv - 没有正确读取字符串值

[英]NodeJS dotenv - Not reading string value properly

I'm trying to us dotenv ( https://github.com/motdotla/dotenv ) in nodeJS to store the client secret value for an oauth server I'm using.我正在尝试在dotenv ( https://github.com/motdotla/dotenv ) 来存储我正在使用的 oauth 服务器的客户端机密值。

My .env file looks like the following:我的.env文件如下所示:

clientSecret=imU86A3oPiZlyOhZybShraP377ers0MvowBaizEQ

Within the NodeJS file, I have the following:在 NodeJS 文件中,我有以下内容:

passport.use(new PasswordGrantStrategy({
    tokenURL: 'WEBSITE_ADDRESS',
    clientID: "2",
    clientSecret: process.env.clientSecret,
    grantType: "password",

},

The problem is that I get a Token Error but, if I change it the following:问题是我收到了一个Token Error但是,如果我将其更改为以下内容:

passport.use(new PasswordGrantStrategy({
    tokenURL: 'WEBSITE_ADDRESS',
    clientID: "2",
    clientSecret: "imU86A3oPiZlyOhZybShraP377ers0MvowBaizEQ",
    grantType: "password",

},

This then works perfectly fine.这然后工作得很好。 I don't understand what the problem could be and I've tried to cast it as a string but no such luck.我不明白问题可能是什么,我试图将它转换为字符串,但没有这样的运气。

The values are both matching and I'm printing them out and they are both the same.这些值都匹配,我将它们打印出来,它们都是相同的。

使用反引号包裹字符串值,您的生活将变得轻而易举!

clientSecret=`imU86A3oPiZlyOhZybShraP377ers0MvowBaizEQ`

Make sure you have dotenv installed Make sure you config dotenv as early as possible in your app确保已安装 dotenv 确保尽早在应用程序中配置dotenv

require('dotenv').config({path: __dirname + '/.env'});

note: good idea to use the path parameter in some setups, for example if using a debugger otherwise dotenv may not find and load the .env file.注意:在某些设置中使用path参数是个好主意,例如,如果使用调试器,否则 dotenv 可能找不到并加载 .env 文件。

If you need to set dynamically the environment value in you app variable如果您需要在应用变量中动态设置环境值

 for(const [keyObj, valObj] of Object.entries(data)){
     for(const [key, value] of Object.entries(valObj)){
         app.set(key.toLocaleLowerCase(), value);
     }
 }

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

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