websocket - @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;
}
}
有没有人遇到过这样的错误以及如何解决?
解决方案
"@nestjs/websockets": "^6.8.2"
发现问题, &之间的包冲突"@nestjs/core": "^6.0.0",
。我需要升级所有@nestjs 包
推荐阅读
- docker - 在 pptpd vpn 服务器之后运行 docker 容器时的 tls 握手超时
- vba - 查明是否在 MS Access 中打开了多个表单之一
- java - Groovy spock 测试用例找不到自动装配的 bean
- c# - 在谓词中动态选择参数的通用方法
- javascript - 识别元素中的随机背景梯度函数问题
- java - 等待多个线程完成
- python - python中的“具有多个元素的数组的真值不明确”
- python-3.x - Pandas 0.25.0 无法为 read_sql 创建游标 - 抛出错误
- javascript - 选择日期后模拟输入键(jquery)
- object-detection - 带有 TensorFlow Objection Detection API V2 的多通道输入