我在用typeorm和postgres连接到nest.js数据库时遇到了问题。
我在根项目目录中创建了一个.env文件,其内容如下
POSTGRES_HOST=127.0.0.1
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=password
POSTGRES_DATABASE=db-name在app.module.ts中,我编写了以下代码:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { FeedModule } from './feed/feed.module';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRoot({
type: 'postgres',
host: process.env.POSTGRES_HOST,
port: parseInt(<string>process.env.POSTGRES_PORT),
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DATABASE,
autoLoadEntities: true,
synchronize: true,
}),
FeedModule,
],
})
export class AppModule {}但是当im通过npm启动运行应用程序时,它会抛出以下错误:new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string')
我错过了什么或者做错了什么?
发布于 2022-01-24 10:37:53
在NestJs中,您应该使用ConfigService获取您的typeorm模块中的环境变量,阅读文档获取更多信息。
你可以这样用它:
import { ConfigModule, ConfigService } from '@nestjs/config';
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
ConfigModule.forRoot(
envFilePath: `.${process.env.NODE_ENV}.env`
),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
injects: [ConfigService],
useFactory: (configService: ConfigService) => ({
type: 'postgres',
host: configService.get("POSTGRES_HOST"),
port: configService.get("POSTGRES_PORT"),
username: configService.get("POSTGRES_USER"),
password: configService.get("POSTGRES_PASSWORD"),
database: configService.get("POSTGRES_DB"),
entities: [],
synchronize: true,
}),
}),
],
controllers: [],
providers: [],
})
export class AppModule {}发布于 2021-12-29 10:06:23
正如在文档中所解释的,您可以定义一个工厂函数,在其中注入配置服务,允许您解析相应的值:
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'postgres',
host: configService.get('POSTGRES_HOST'),
port: +configService.get<number>('POSTGRES_PORT'),
username: configService.get('POSTGRES_USER'),
password: configService.get('POSTGRES_PASSWORD'),
database: configService.get('POSTGRES_DATABASE'),
synchronize: true,
autoLoadEntities: true,
}),
inject: [ConfigService],
});发布于 2022-06-16 22:56:04
我能够通过使用config模块来解决这个问题。
只要做npm i @nestjs/config。然后,在TypeOrmModule put ConfigModule.forRoot({ isGlobal: true }),之上的imports数组中。这允许模块从.env文件中获取环境变量。
https://stackoverflow.com/questions/70517803
复制相似问题