Home > front end >  Can't establish connection between VueJS 3 and Socket.io
Can't establish connection between VueJS 3 and Socket.io

Time:11-20

I am completely new to Socket.IO and generally to Back-end technologies. However, I have experience with Vue and I am trying to create a simple multiplayer game.

But I am stuck on the first step... connecting vueJS and SocketIO.

Here is the server:

const app = express()
const http = require("http");
const server = http.createServer(app)

const io = require('socket.io')(8000);

io.on('connection', function(socket) {
  console.log('new connection');

  socket.on('updateUsers', function(data) {
    console.log('event received');
  });
})

This is the main.js:

import VueSocketIO from 'vue-socket.io'
import SocketIO from "socket.io-client"

import "./assets/main.css";

const app = createApp(App);

app.use(router, new VueSocketIO({
    debug: true,
    connection: SocketIO('http://localhost:5173/'), 
    }));

app.mount("#app");

And the homepage.vue:

import io from 'socket.io-client';
data() {
    return {
      socket: io()
    }
  },
methods: {
    startGame() {this.socket.emit('updateUsers', "someUser")
    },
}

So neither the "new connection" from the server is rendered in the terminal, nor the front-end is able to send events(no errors, but also nothing happens) Do you see anything wrong? Could it be something with the router or because I pass two arguments to the app?

app.use(router, new VueSocketIO...)

CodePudding user response:

Can you add this express middleware code to allow cross origin request in the Socket IO Server.

app.use(function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  next()
})

CodePudding user response:

Found the issue and it's almost stupid. The socket library doesn't support VueJS 3, it supports only vueJS 2. So there are 2 alternatives to get this working, the first is Vue-3-Socket.io and the second is this alpha version of Vue-Socket.io-Extended. I went for the second one and it gets the work done.

  • Related