标签: nestjs

在 Node 框架 NestJS-6.3.1 中面对 CORS

我正在使用 nestJs => 6.3.1 框架开发一个 Node 基础项目。我已启用所有 cors 仍然面临以下错误

CORS 策略已阻止从源“ http://localhost:4200 ”访问“localhost:3000”处的 XMLHttpRequest :跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。

core.js:7187 错误 HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "localhost:3000", ok: false, ...}

我尝试了以下方法,但仍然面临同样的问题。

1. var app = await NestFactory.create(AppModule,{cors:true}); 等待 app.listen(3000);

  1. var app = await NestFactory.create(AppModule); const options = { origin: '*', methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', preflightContinue: false, optionsSuccessStatus: 204, credentials: true, allowedHeaders: 'Content-Type, Accept', }; 控制台日志(应用程序);app.enableCors(选项); 等待 app.listen(3000);

    import { NestFactory } from '@nestjs/core';
    import { AppModule } from './app/app.module';
    
    async function bootstrap() …
    Run Code Online (Sandbox Code Playgroud)

nestjs

2
推荐指数
1
解决办法
2683
查看次数

Nest.js 中特定路由上的 WebSockets

我想创建特定的 API 路由,该路由将仅用于 WebSocket ( /api/events) 但在 Nest.js 上实现 WebSockets 的所有示例中,我偶然发现模块被导入AppModule并且客户端正在向根 URL 发出事件,我不能这样做是因为我有这个中间件;

前端.middleware.ts

import { Request, Response } from 'express';
import { AppModule } from '../../app.module';

export function FrontendMiddleware(
  req: Request,
  res: Response,
  next: Function,
) {
  const { baseUrl } = req;
  if (baseUrl.indexOf('/api') === 0) {
    next();
  } else {
    res.sendFile('index.html', { root: AppModule.getStaticAssetsRootPath() });
  }
}
Run Code Online (Sandbox Code Playgroud)

这是EventGatewayEventModule

event.gateway.ts

import {
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
  WsResponse,
} from '@nestjs/websockets';
import { …
Run Code Online (Sandbox Code Playgroud)

controller websocket nestjs

2
推荐指数
2
解决办法
3858
查看次数

NestJS:在开发模式下找不到模块

在此处输入图片说明

我在使用 NestJS 的应用程序的开发模式中遇到此错误。

我的配置文件如下:

export const ORM_CONFIG: TypeOrmModuleOptions = {
  keepConnectionAlive: true,
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  username: 'postgres',
  password: 'postgres',
  database: 'aimbra_education',
  schema: 'security',
  synchronize: true,
  entities: [
   --Entities
  ],
  // migrations: [__dirname + '/migration/**/*.ts'],
  // subscribers: [__dirname + '/subscriber/**/*.ts'],
};
Run Code Online (Sandbox Code Playgroud)

我导入到:

@Module({
  imports: [
    TypeOrmModule.forRoot(ORM_CONFIG),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Run Code Online (Sandbox Code Playgroud)

到目前为止,我无法确定为什么它在生产中工作并且在开发模式下无法查看我的修改的错误。

typescript typeorm nestjs

2
推荐指数
1
解决办法
5590
查看次数

如何在模块导入/配置中设置 .env 变量

我想.env在我的应用程序中使用一个文件。

我为此创建了两个文件(一个模块和一项服务):

config.module.ts

import {Module} from '@nestjs/common';
import {ConfigService} from './config.service';

@Module({
    providers: [{
        provide: ConfigService,
        useValue: new ConfigService(`${process.env.NODE_ENV || 'development'}.env`),
    }],
    exports: [ConfigService],
})

export class ConfigModule {}
Run Code Online (Sandbox Code Playgroud)

config.service.ts

import * as dotenv from 'dotenv';
import * as fs from 'fs';

export class ConfigService {
    private readonly envConfig: {[key: string]: string};

    constructor(filePath: string) {
        // stock the file
        this.envConfig = dotenv.parse(fs.readFileSync(filePath));
    }

    // get specific key in .env file
    get(key: string): string {
        return this.envConfig[key];
    }

} …
Run Code Online (Sandbox Code Playgroud)

javascript dependency-injection node.js typescript nestjs

2
推荐指数
1
解决办法
1900
查看次数

NestJS:如何获取猫鼬的实例进行健康检查?

我正在使用 @nestjs/mongoose 包连接到 Mongo DB。我在 app.module.ts 中有这个:

imports: [
   MongooseModule.forRoot(process.env.MONGODB_URI, {
      useNewUrlParser: true,
      bufferCommands: false,
      bufferMaxEntries: 0,
      useCreateIndex: true,
      useFindAndModify: false,
      useUnifiedTopology: true
})]
Run Code Online (Sandbox Code Playgroud)

现在,NestJS 服务在 Kubernetes 集群中运行,并进行了适当的健康、活跃度和就绪检查。每当在服务上调用就绪或运行状况端点时,我需要检查托管的 Atlas Mongo DB 连接是否可用或是否发生中断。截至目前,为就绪和健康端点执行以下代码:

this.mongoDbConnection = await mongoose.connect(process.env.MONGODB_URI, options);
return (this.mongoDbConnection.connection.readyState === 1);
Run Code Online (Sandbox Code Playgroud)

但这会创建与 mongo DB 服务器的新连接。我想要的是检索 NestJS 通过 app.module.ts 中的 MongooseModule.forRoot 建立的现有连接的 readyState。

我不确定如何在健康检查服务代码中检索现有的猫鼬连接对象。任何帮助将非常感激。

mongoose mongodb node.js nestjs

2
推荐指数
2
解决办法
4674
查看次数

如何使用 NestJS 和类验证器手动测试输入验证

TLNR:我试图在控制器规范中而不是在 e2e 规范中测试 DTO 验证,后者正是为此而设计的。McDoniel 的回答为我指明了正确的方向。


我开发了一个 NestJS 入口点,如下所示:

@Post()
async doStuff(@Body() dto: MyDto): Promise<string> {
  // some code...
}
Run Code Online (Sandbox Code Playgroud)

我使用class-validator这样当我的 API 收到请求时,有效负载被解析并转换为 MyDto 对象,并执行作为 MyDto 类中的注释的验证。请注意,MyDto 有一个 MySubDto 类的嵌套对象数组。使用@ValidateNested 和@Type 注释,嵌套对象也可以正确验证。

这很好用。

现在我想为执行的验证编写测试。在我的 .spec 文件中,我写道:

import { validate  } from 'class-validator';
// ...
it('should FAIL on invalid DTO', async () => {
  const dto = {
    //...
  };
  const errors = await validate( dto );
  expect(errors.length).not.toBe(0);
}
Run Code Online (Sandbox Code Playgroud)

这将失败,因为经过验证的 dto 对象不是 MyDto。我可以这样重写测试:

it('should FAIL on invalid DTO', …
Run Code Online (Sandbox Code Playgroud)

testing validation dto nestjs

2
推荐指数
2
解决办法
4541
查看次数

Nest 无法解析 UserModel 的依赖关系 (?)

当我尝试使用MongooseModelUsers我收到以下错误

Nest 无法解析 UserModel (?) 的依赖关系。请确保索引 [0] 处的参数 DatabaseConnection 在 MongooseModule 上下文中可用。

/src/database/database.module.ts

import { Module } from '@nestjs/common';
import { databaseProviders } from './database.providers';
import { ConfigModule } from '../config/config.module';

@Module({
  imports: [ConfigModule],
  providers: [...databaseProviders],
  exports: [...databaseProviders],
})
export class DatabaseModule {}
Run Code Online (Sandbox Code Playgroud)

/src/database/database.provider.ts

// NPM Packages
import * as mongoose from 'mongoose';
import { Provider } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';

// Custom Packages
import { ConfigService } from '../config/config.service';

export const …
Run Code Online (Sandbox Code Playgroud)

javascript mongoose node.js typescript nestjs

2
推荐指数
1
解决办法
3405
查看次数

从 HttpModule 中的 RxJS observable 中检索数据

我无法理解如何mapHttpServiceNestJS 应用程序中取出数据属性。据我了解,这Observable只是包装axios. 下面是一些示例代码:

interface Todo {
   task: string,
   completed: false
}

import {
  Injectable,
  HttpService,
  Logger,
  NotFoundException,
} from '@nestjs/common'
import { map } from 'rxjs/operators

async getTodo(todoUrl: string): Todo {
   const resp = this.httpService
      .get('https://example.com/todo_json')
      .pipe(map(response => response.data)) // map task/completed properties?
   return resp
}
Run Code Online (Sandbox Code Playgroud)

resp在这种情况下似乎是类型Observable。如何仅检索我想map在此请求中使用的数据属性以返回我的Todo界面?

observable rxjs axios nestjs

2
推荐指数
1
解决办法
2705
查看次数

Nodejs/NestJS ExceptionFilter Catch 方法的 Jest 单元测试

这是我用 Typescript 为 Nodejs/Nestjs 编写的 BadRequestExceptionFilter


@Catch(BadRequestException)
export class BadRequestExceptionFilter implements ExceptionFilter {
  constructor(private logger: AppLoggerService) {}
  catch(exception: BadRequestException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    const status =
      exception instanceof BadRequestException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const message = {
      Title: exception.message.error,
      Type: 'Exception - BadRequestExceptionFilter',
      Detail: exception.message,
      Status: '',
    };

    this.logger.error(message, '');
    response.code(status).send({
      statusCode: status,
      ...(exception.getResponse() as object),
      timestamp: 'Exception - BadRequestException' + new Date().toISOString(),
    });
  }
}

Run Code Online (Sandbox Code Playgroud)

这是我的单元测试和 2 个断言在这里完成。第一个断言是检查是否调用了 …

unit-testing node.js typescript jestjs nestjs

2
推荐指数
2
解决办法
2907
查看次数

所有控制器的全局标头(nestJs swagger)

有没有办法将所需的标头全局添加到 NestJS 中的所有端点/控制器?

有一个控制器绑定装饰器@ApiHeader。有没有办法将其应用于所有端点?

swagger nestjs

2
推荐指数
1
解决办法
1057
查看次数