首页 > 解决方案 > 如何修复套接字 io 中的 400 错误错误请求?

问题描述

我有一个前端应用程序(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");
      },
    },
}

标签: javascriptvue.jswebsocketsocket.ionestjs

解决方案


在服务器端尝试以下配置

const io = require('socket.io')(server, {
    cors: {
        origin: "http://localhost:8100",
        methods: ["GET", "POST"],
        transports: ['websocket', 'polling'],
        credentials: true
    },
    allowEIO3: true
});

推荐阅读