首页 > 解决方案 > @nestjs/websockets with Guards 因 host.setType 而失败

问题描述

我正在尝试将 JWT 身份验证添加到 nestJs WebSockets。
我能够从客户端连接并发送标头。
但是,TypeError: host.setType is not a function当我使用警卫设置 nestJs WebSocket 时出现错误。 在此处输入图像描述

错误源自 ws-proxy.js 在此处输入图像描述 的返回值ExecutionContextHost没有调用的属性/方法,setType但在第 27 行:它被使用

我的 Guard.ts 文件如下。

import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import * as configs from 'config';
import { Socket } from 'socket.io';
import { JwtService } from '@nestjs/jwt';
import { JwtPayload } from '../jwt-payload.interface';
import { WsException } from '@nestjs/websockets';

@Injectable()
export class JwtGuard implements CanActivate {
  constructor(private readonly jwtService: JwtService) { }

  async canActivate(context: ExecutionContext): Promise<boolean> {

    try {
      const client: Socket = context.switchToWs().getClient<Socket>();
      const authHeader: string = client.handshake.headers.authorization;
      const authToken = authHeader.substring(7, authHeader.length);
      const jwtPayload: JwtPayload = await this.jwtService.verifyAsync(authToken, configs.get('JWT.publicKey'));
      const user: any = this.validateUser(jwtPayload);

      context.switchToWs().getData().user = user;
      return Boolean(user);
    } catch (err) {
      throw new WsException(err.message);
    }
  }

  validateUser(payload: JwtPayload): any {
    return payload;
  }
}

套接字文件是

import { SubscribeMessage, WebSocketGateway } from '@nestjs/websockets';
import { Socket } from 'socket.io';
import { UseGuards} from '@nestjs/common';
import { JwtGuard } from '../../../common/authentication/jwt-guard/jwt.guard';

@UseGuards(JwtGuard)
@WebSocketGateway()
export class ContractGateway {
  @SubscribeMessage('message')
  handleMessage(client: Socket, payload: any): Boolean {
    return true;
  }
}

有没有人遇到过这样的错误以及如何解决?

标签: websocketnestjs

解决方案


"@nestjs/websockets": "^6.8.2"发现问题, &之间的包冲突"@nestjs/core": "^6.0.0",。我需要升级所有@nestjs 包


推荐阅读