I have a frontend application(VUE JS)
I have a backend (Nest JS)
Vue JS app get data from backend via websockets using vue-socket.io-extended library When Vue JS app starts I see errors in browser:
polling-xhr.js?d33e:229 POST http://localhost:11050/socket.io/?EIO=4&transport=polling&t=NMXgCF1 400 (Bad Request)
How can I fix this error?
I think it is not connected with library, I tried just socket io library and the result was the same.
Server is working, because it sends logs and show who is connected:
Server(Nest JS) main.ts file:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
await app.listen(11050);
}
bootstrap();
App.gateway:
@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}`);
}
}
Frontend(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");
},
},
}
First and foremost, please note that disconnections are common and expected, even on a stable Internet connection: anything between the user and the Socket.IO server may encounter a temporary failure or be restarted.
The error message “ERR_SOCKET_NOT_CONNECTED” is instantly solved in the majority of the cases when we flush the sockets on your browser. This will break the connection between any active pages on your browser and you might have to reinitialize everything.
You can check the socket. connected property: var socket = io. connect(); console.
I ran into this issue today using a very similar NestJS implementation, however my frontend is written with ReactJS. I believe the issue is related to mismatched socket.io server and client versions.
I resolved this issue by downgrading the version of socket.io-client
from ^3.0.0
down to ^2.3.0
.
Try below configuration on server side
const io = require('socket.io')(server, {
cors: {
origin: "http://localhost:8100",
methods: ["GET", "POST"],
transports: ['websocket', 'polling'],
credentials: true
},
allowEIO3: true
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With