标签: nestjs

使用接口对传入请求进行 NestJS 类验证器

我需要通过类验证器使用接口来验证传入请求正文中特定字段的传入表单。

界面:

export enum Fields {
  Full_Stack_Dev = 'full stack dev',
  Frontend_Dev = 'frontend dev',
  Backend_Dev = 'backend dev',
}

export interface Experience {
  field: Fields;
  years: number;
}
Run Code Online (Sandbox Code Playgroud)

这是DTO课程:

@IsEnum(Languages)
  languages: Languages[];

  experience: Experience[]; //  Not sure which decorator to use for interfaces 
Run Code Online (Sandbox Code Playgroud)

node.js typescript class-validator nestjs

0
推荐指数
1
解决办法
4239
查看次数

在 Nestjs 中使用 multipart/form-data

我需要将 pdf 文件上传到第三方 API 来执行我们使用控制器的操作,然后将其缓冲区发送到 multipart/form-data 中的端点,但它不起作用。我究竟做错了什么??

我的控制器定义如下

    @Post('/upload')
    @UseInterceptors(FileInterceptor('file'))
    async uploadDocument(@UploadedFile() file: Express.Multer.File){
        await this.httpRequestService.uploadDocument(file)
        return [
            Translation.translate('Create_Success_Message', {
                Entity: 'File'
            }),
            {
                file
            }
        ]
    }
Run Code Online (Sandbox Code Playgroud)

该控制器调用一个名为的服务,uploadDocument如下所示:

async uploadDocument(file){
        try{
        const formData = new FormData()
        formData.append('file', file)
        const response = await this.httpService.post(`urlWhereItHits`,
        formData, 
        {   
            headers:{ 
                "X-AppSecretToken":"appsecrettoken",
                "X-AgreementGrantToken":"agreementgranttoken",
                'Content-Type' : 'multipart/form-data'
            },
            
        }).toPromise();
        }
        catch(error){
            console.log(error)
        }
}
Run Code Online (Sandbox Code Playgroud)

现在我不明白这里发生了什么问题。我收到错误消息
TypeError: source.on is not a function at Function.DelayedStream.create (C:\Users\Tushar\Squire-backend\node_modules\delayed-stream\lib\delayed_stream.js:33:10)

nestjs

0
推荐指数
1
解决办法
9778
查看次数

如何在 JWTStrategy (NestJS) 中获取用户 JWT 令牌?

我的问题是我想检查数据库中的登录令牌是否无效(更改密码后)。但是,JWTStrategy 中的验证函数只能访问 JWT 的有效负载,而不能访问令牌。我想知道是否有办法可以从此类或 JWTAuthGuard 的请求中获取 JWT 令牌。谢谢!

  async validate(payload: LoginPayload) {
    const { email, firstName, lastName, sub } = payload;
    return {
      id: sub,
      email,
      firstName,
      lastName,
    };
  }
Run Code Online (Sandbox Code Playgroud)

jwt nestjs

0
推荐指数
1
解决办法
2538
查看次数

在 Nestjs 中发送带有 headers 的 Post 请求

我正在尝试使用 Nestjs 向需要授权(客户端密钥和秘密)的第三方 API 发送 Post 请求。有人知道如何在请求中附加标头吗?我想使用axio的HttpService。

request node.js express typescript nestjs

0
推荐指数
1
解决办法
7310
查看次数

Salesforce - unsupported_grant_type:不支持授权类型

我在NestJS ( Typescript ) 应用程序中使用JSforceOAuth2连接到我的Salesforce帐户时遇到问题。

这是我的登录代码:

@Get('salesforce/login/:userId')
  async login(@Req() req, @Res() res, @Param('userId') userId) {
    const user = await this.userService.findById(userId);
    const oauth2 = new OAuth2({
      loginUrl: user.salesforceOauthInformation.loginUrl,
      clientId: user.salesforceOauthInformation.clientId,
      clientSecret: user.salesforceOauthInformation.clientSecret,
      redirectUri: user.configService.salesforceRedirectUri,
    });
    res.redirect(
      oauth2.getAuthorizationUrl({
        scope: 'api full id web refresh_token',
        state: user.id,
      }),
    );
  }
Run Code Online (Sandbox Code Playgroud)

这是我的回调代码:

@Get('salesforce/callback')
  async callback(@Query('code') code: string, @Query('state') state: string) {
    const user = await this.userService.findById(state);
    const oauth2 = new OAuth2({
      loginUrl: user.salesforceOauthInformation.loginUrl,
      clientId: user.salesforceOauthInformation.clientId,
      clientSecret: user.salesforceOauthInformation.clientSecret,
      redirectUri: …
Run Code Online (Sandbox Code Playgroud)

salesforce oauth-2.0 typescript nestjs jsforce

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

如何向 NestJS v8 + GraphQL 中的所有响应添加标头?

我想向 NestJS 框架(v8)中的所有响应添加具有值的自定义标头。我认为正确的方法是使用全局拦截器,但我不知道该怎么做。

我正在添加我的拦截器:

app.useGlobalInterceptors(new HeadersInterceptor());
Run Code Online (Sandbox Code Playgroud)

我发现了多种方法,但没有一个有效。最常见的看起来像:

import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable, tap } from 'rxjs';

@Injectable()
export class HeadersInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      tap(() => {
        const res = context.switchToHttp().getResponse();

        res.setHeader('my-global-header', 'important-value');
      }),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

但我收到错误:

res.setHeader is not a function
Run Code Online (Sandbox Code Playgroud)

编辑:从正确的答案来看,我应该提到我也在使用 GraphQL。

javascript response-headers typescript graphql nestjs

0
推荐指数
1
解决办法
2956
查看次数

如何通过 Nest-commander 创建和使用终端命令?

所以,我有这个 NestJS 项目,出于学习目的,我想使用Nest-commander创建一个可以在终端上执行的命令(这样我可以从其他服务调用函数),也出于学习目的,每当我调用它时命令,它应该调用服务文件上的函数,从数据库中获取用户。

它看起来像这样:

> run myCommand -username UsernameString
Run Code Online (Sandbox Code Playgroud)

每当从终端调用该命令时,我都会调用getUser()fromAnotherService来查找具有特定 UsernameString 的用户。我阅读了文档,但无法理解其中的内容,所以......

  1. 如何从终端调用命令?
  2. 是否可以在应用程序中调用相同的命令?

javascript node.js typescript node-commander nestjs

0
推荐指数
1
解决办法
6086
查看次数

Nest.js 路由参数没有返回任何内容

我开始学习 Nest.js。现在我想了解路由参数是如何工作的。

我有一个带有以下代码的控制器。

import {Controller, Get, Param, Req, Res} from '@nestjs/common';
import { AppService } from './app.service';
import {Request, Response} from "express";

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get(':name')
  getHello(@Param('name') name: string,
           @Req() req: Request,
           @Res() res: Response): string {
    return name;
  }
}
Run Code Online (Sandbox Code Playgroud)

正如您在代码中看到的,我正在尝试检索名称参数。但是当我在浏览器中访问此 URL http://localhost:3000/?name=test 时,出现以下错误。

http://localhost:3000/?name=test
Run Code Online (Sandbox Code Playgroud)

当我访问此 URL http://localhost:3000/test 时,它只会继续加载页面。我的代码有什么问题以及如何修复它?

node.js nestjs

0
推荐指数
1
解决办法
5623
查看次数

JEST 的 Nestjs 日志服务

在 Jest 中执行时,我在查看 Nestjs 内的日志时遇到问题。我可以设置在运行 Nestjs 时查看记录器,但通过 Jest 运行时。记录器未打印在屏幕上。

以下是用于设置测试模块的代码。

const module: TestingModule = await Test.createTestingModule({
  imports: [HttpModule, ScheduleModule.forRoot()],
  controllers: [ExampleController],
  providers: [ExampleService, Logger],
}).compile();

module.useLogger(['error', 'warn', 'log', 'debug', 'verbose']);
Run Code Online (Sandbox Code Playgroud)

在ExampleController中

import { Controller, Get, Logger } from '@nestjs/common';

@Controller('example')
export class ExampleController {
  private readonly logger = new Logger(ExampleController.name);

  @Get()
  getExample(): string {
    this.logger.debug('example');
    return 'example';
  }
}
Run Code Online (Sandbox Code Playgroud)

在 Jest 上运行时不会显示此调试消息。

logging jestjs nestjs

0
推荐指数
1
解决办法
892
查看次数

使用 NestJS 中的类验证器进行电子邮件验证

我想做的是当有人尝试使用已在使用的电子邮件进行注册时传播错误。默认情况下,这会返回 500 错误,但我需要它针对此特定场景抛出有意义的错误。注意:程序对于每个错误都会返回 500 错误

email-validation class-validator nestjs

0
推荐指数
1
解决办法
7138
查看次数