node.jssocketsvue.jssocket.iovue-socket.io

vue-socket.io app not receiving emit from express socket.io app


I am trying to create a socket.io communication between an express app using socket.io (localhost:8000) and a vue app using vue-socket.io (localhost:8080). The express app is receiving emissions from the vue app but not vice versa. Here is my express app though I'm pretty sure the problem lies in the vue app:

Backend Express

const port = 8000
const express = require("express")
const socket = require("socket.io")

const app = express()
const server = app.listen(port, () => {
  console.log(`App is lisening to port ${port}...`)
} )

const io = socket(server)

io.on("connection", (socket) => {
  console.log("connected to " + socket.id) //this is successfully getting logged
  socket.on("chat", (msg) => {
    console.log(socket.id + ": " + msg) //this is successfully getting logged when I click send
    io.sockets.emit("chat", msg) 
  } )
} )

I'm guessing the problem is somewhere below:

Frontend Vue (using CLI)

main.js:

import Vue from 'vue'
import App from './App.vue'
import VueSocketIO from 'vue-socket.io'
import SocketIO from 'socket.io-client'

Vue.use(new VueSocketIO( {
    debug: true,
    connection: SocketIO('http://localhost:8000')
  } )
)

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

Chat component (Chat.vue)

<template lang="html">
  <div>
    <input type="text" v-model="input"/>
    <button @click="send">Send</button>
  </div>
</template>

<script>
export default {
  sockets: {
    //These dont work, nothing is printed to the console
    connect: function () {
      console.log('socket connected')
    },
    chat: function (msg) {
      console.log("chat message recieved!: " + msg)
    }
  },
  data(){
    return {
      input: ""
    }
  },
  methods: {
    send(){
      this.$socket.emit('chat', this.input) //This works and is recieved by the express app!
    }
  }
}
</script>

I've been trying to figure this out for a day now with no luck.

Once again my only goal is to be able to receive emissions front the express app. As a side note if there is a better way to use socket.io in vue without using vue-socket.io I would be glad to investigate.


Solution

  • I was able to get this working simply by using vue-socket.io-extended instead of vue-socket.io. That was it, no major changes to the code necessary. I know technically this doesn't solve the issue using vue-socket.io, but until someone figures that out, I will leave this as the answer for future searchers.