NestJS 返回 201 OK 状态,即使在响应中我收到未经授权的错误消息

问题描述 投票:0回答:1

我使用 NestJS 作为后端框架,在执行登录服务时,它没有返回有效的 HTTP 代码。我在应用程序上使用了 GlobalPipes,因为它将显示在提供的代码中。另外,发送错误消息的代码部分正在被激活,它发送我放在那里的错误消息,但响应仍然有一个错误的代码。

这是登录码

async login(dto: LoginDto) {
    try {
      const user = await this.prisma.user.findUnique({
        where: {
          email: dto.email,
        },
      });

      if (!user) throw new ForbiddenException('Credentials incorrect');

      const pwMatches = await argon.verify(user.password, dto.password);

      if (!pwMatches) throw new ForbiddenException('Credentials incorrect');
      return this.signToken(user.id, user.email);
    } catch (error) {
      return error;
    }
  }
javascript http backend nest
1个回答
0
投票

我遇到了类似的问题,偶然发现了你的问题,并意识到可能会发生什么。问题在于您返回了一个错误对象,这导致 NestJS 对其进行序列化并为 POST 请求返回 HTTP 状态 201。

当引发异常时,无论是由您的代码还是更可能由 ORM 引发,您将立即进入 catch 块。为了解决这个问题,您应该在 catch 块中抛出异常,以将 ForbiddenException 正确传播到控制器,而不是返回错误对象。

async login(dto: LoginDto) {
try {
  const user = await this.prisma.user.findUnique({
    where: {
      email: dto.email,
    },
  });

  if (!user) return new ForbiddenException('Credentials incorrect');

  const pwMatches = await argon.verify(user.password, dto.password);

  if (!pwMatches) return new ForbiddenException('Credentials incorrect');
  return this.signToken(user.id, user.email);
} catch (error) {
 // put some logs here
 // some error handling
throw InternalServerException(`Something went wrong: error?.message`)
}

}

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.