从Nestjs中的自定义函数访问本地.ENV变量
我有一个带有以下变量的.env.development
文件
DB_NAME=db.sqlite
COOKIE_KEY=sdfjshdfjsf
,我创建了一个setup-app.ts
用setupapp
函数,在哪里定义了cookie 键
值:
import { ValidationPipe } from '@nestjs/common';
const cookieSession = require('cookie-session');
export const setupApp = (app: any) => {
app.use(
cookieSession({
keys: ['asdfasdf'],
}),
);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
}),
);
};
如何正确访问此.ENV变量(cookie_key = sdfjshdfjsf
) setupapp
函数?稍后,我想将我的应用上传到Heroku,并在此处创建此cookie_key
变量。因此,它也应该以后与Heroku一起使用。
我在Nestjs找到了通过这种方法来进行此操作的方法,
keys: [this.configService.get('COOKIE_KEY')]
但是这显然需要类
在structionor
和进一步复杂的配置中进行依赖项注入。就我而言,我只有一个功能。
I have an .env.development
file with the following variables
DB_NAME=db.sqlite
COOKIE_KEY=sdfjshdfjsf
For this I have created a setup-app.ts
file with the setupApp
function, where I defined a cookie keys
value:
import { ValidationPipe } from '@nestjs/common';
const cookieSession = require('cookie-session');
export const setupApp = (app: any) => {
app.use(
cookieSession({
keys: ['asdfasdf'],
}),
);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
}),
);
};
How to properly access this .env variable (COOKIE_KEY=sdfjshdfjsf
) value within my setupApp
function? Later I want to upload my app to Heroku and also create this COOKIE_KEY
variable there. So it should also work later with Heroku.
I found a way in NestJS to do this via
keys: [this.configService.get('COOKIE_KEY')]
but this apparently requires a class
with a dependency injection in the constructor
and further complicated configurations. In my case I have only a function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只是nodejs。如果您想加载env。将
process.env
对象的文件归档,您可以使用一些lib,例如
。dotenv
@nestjs/config
使用lib btwit's just nodejs. If you want to load your env. file into
process.env
object, you can use some lib likedotenv
.@nestjs/config
uses that lib btw创建configservice的新实例,然后使用configservice.get
Create new instance of ConfigService then use configService.get