我有一个前端应用程序(VUE JS)
我有一个后端(Nest JS)
Vue JS 应用程序使用 vue-socket.io-extended 库通过 websockets 从后端获取数据当 Vue JS 应用程序启动时,我在浏览器中看到错误:
polling-xhr.js?d33e:229 POST http://localhost:11050/socket.io/?EIO=4&transport=polling&t=NMXgCF1 400(错误请求)
我该如何解决这个错误?
我认为它没有与库连接,我只尝试了 socket io 库,结果是一样的。
服务器正在运行,因为它发送日志并显示谁已连接:
服务器(Nest JS) main.ts 文件:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
await app.listen(11050);
}
bootstrap();
应用网关:
@WebSocketGateway()
export class AppGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
private logger: Logger = new Logger('AppGatway');
@SubscribeMessage('msgToServer')
handleMessage(client: Socket, text: string): WsResponse<string> {
return { event: 'msgToClient', data: text };
}
afterInit(server: Server) {
this.logger.log('Initialised!');
}
handleConnection(client: Socket, ...args: any[]): any {
this.logger.log(`Client connected: ${client.id}`);
}
handleDisconnect(client: Socket): any {
this.logger.log(`Client disconnected: ${client.id}`);
}
}
前端(Vue JS):
import VueSocketIOExt from "vue-socket.io-extended";
import Vue from "vue";
import io from "socket.io-client";
const socket = io("http://localhost:11050/");
Vue.use(VueSocketIOExt, socket);
data: () => ({
socket: null,
connection: null,
sockets: {
connect() {
console.log("socket connected");
},
},
}
原文由 kentforth 发布,翻译遵循 CC BY-SA 4.0 许可协议
我今天使用非常相似的 NestJS 实现遇到了这个问题,但是我的前端是用 ReactJS 编写的。我认为这个问题与不匹配的 socket.io 服务器和客户端版本有关。
我通过将
socket.io-client
的版本从^3.0.0
降级到^2.3.0
解决了这个问题。