ken*_*rth 10 javascript websocket socket.io vue.js nestjs
我有一个前端应用程序(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();
Run Code Online (Sandbox Code Playgroud)
应用网关:
@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}`);
}
}
Run Code Online (Sandbox Code Playgroud)
前端(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");
},
},
}
Run Code Online (Sandbox Code Playgroud)
Roh*_*t M 14
在服务器端尝试以下配置
const io = require('socket.io')(server, {
cors: {
origin: "http://localhost:8100",
methods: ["GET", "POST"],
transports: ['websocket', 'polling'],
credentials: true
},
allowEIO3: true
});
Run Code Online (Sandbox Code Playgroud)
wil*_*208 10
我今天使用非常相似的 NestJS 实现遇到了这个问题,但是我的前端是用 ReactJS 编写的。我相信这个问题与不匹配的 socket.io 服务器和客户端版本有关。
我通过将版本socket.io-client从^3.0.0down降级到^2.3.0.
请记住,来源是请求的服务器
const io = SocketIO(server,{
cors: {
origin: "http://localhost",
methods: ["GET", "POST"],
credentials: true,
transports: ['websocket', 'polling'],
},
allowEIO3: true
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9519 次 |
| 最近记录: |