Javascript 未在context.switchToHttp().getRequest()nestjs上定义用户

Javascript 未在context.switchToHttp().getRequest()nestjs上定义用户,javascript,node.js,jwt,nestjs,roles,Javascript,Node.js,Jwt,Nestjs,Roles,我是nestJs新手,需要向应用程序添加基于角色的访问权限,所以我遵循了文档,但在执行上下文中用户不存在。我似乎找不到问题,这里是github repo,如果您需要更多代码: 角色.guard.ts import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import { ROLES_KEY } from 'src/d

我是nestJs新手,需要向应用程序添加基于角色的访问权限,所以我遵循了文档,但在执行上下文中用户不存在。我似乎找不到问题,这里是github repo,如果您需要更多代码:

角色.guard.ts

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from 'src/decorators/roles.decorator';
import Role from 'src/util/enums/role.enum';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const requiredRoles = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (!requiredRoles) {
      return true;
    }
    const { user } = context.switchToHttp().getRequest();
    console.log(context.switchToHttp().getRequest().req);

    return requiredRoles.some((role) => user.type === role);
  }
}
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Get('me/business')
  @Roles(Role.ADMIN)
  getBusiness(@Request() req) {
    return this.usersService.getUserBusiness(req.user.id);
  }

从代码上看,我认为你是全球和本地警卫的混血儿

app.module.ts
中,以下代码用于注册全局防护。 如果要全局应用guard,则应同时使用app.useGlobalGuard()

// Remove the following code in app.module.ts
{
    provide: APP_GUARD,
    useClass: RolesGuard,
}

但是你的意图应该是建立一个本地角色守卫,因此请删除上面的代码,请求用户就会工作。

你是否有机会将
角色守卫
绑定到全球?是的,它在app.module.t中。你能分享你遵循的文档吗?另外,您能否解释一下您如何在请求中发送
用户
?它是在收割台内部还是车身内部?我尝试了你发布的github URL,但我猜它是一个私有存储库,所以我看不见,你现在可以检查吗?我把它公之于众@ErangaHeshan