@dark_king_13

Как заставить Socket.io работать с Vue?

Пытаюсь настроить Socket.io, но в консоли вместо нужного мне сообщения получаю "vendors.101438627b8fbe2d3f90.js:25 POST localhost:3000/socket.io/?EIO=3&transport=polling&... 404 (Not Found)"

Server Express
import { Application, Request, Response } from 'express'
const express = require('express')
const path = require('path')
const fs = require('fs')
const http = require('http')
const consola = require('consola')
const bodyParser = require('body-parser')
const socketIO = require('socket.io')
const connectHistory = require('connect-history-api-fallback')
require('dotenv').config()

function start () {
  try {
    const PORT : number = parseInt(process.env.PORT) || 3000
    const HOST : string = process.env.HOST || 'localhost'
    
    const PATH_TO_CLIENT  = path.join(__dirname, '..', '..', './dist')
    const PATH_TO_HTML  = path.join(PATH_TO_CLIENT, 'index.html')

    fs.stat(PATH_TO_HTML, (err) => {
      if (err) throw consola.error({message: 'index.html is not defined', badge: true,})
    })

    const app : Application = express()
    const server = http.createServer(app)
    const io = socketIO(server)

    app.use(connectHistory())
    app.use(express.static(PATH_TO_CLIENT))
    app.use(bodyParser.json())
    app.use(bodyParser.urlencoded({ extended: true }))
    
    app.get('/', (req : Request, res : Response) => {
      res.sendFile(PATH_TO_HTML)
    })

    app.listen(PORT, HOST, () => {
      consola.ready({
        message: `Server is listening to http://${HOST}:${PORT}`,
        badge: true,
      })
    })

    io.on('connection', (socket) => {
      consola.info({ message: 'Connection is ready' })
    })

  } catch(err) {
    if (err) {
      consola.error({
        message: `ERROR: ${err}`,
        badge: true,
      })
    }
  }
}

start()

Main index.ts
import './assets/scss/main.scss'

import Vue from 'vue'
import App from './App.vue'
import store from './store/index.ts'
import router from './routers/index.ts'
import VueSocketIO from 'vue-socket.io'

Vue.config.productionTip = false

const PORT : number = parseInt(process.env.PORT) || 3000
const HOST : string = process.env.HOST || 'localhost'

Vue.use(new VueSocketIO({
  debug: true,
  connection: `http://${HOST}:${PORT}`,
  vuex: {
      store,
      actionPrefix: 'SOCKET_',
      mutationPrefix: 'SOCKET_'
  },
}))

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

App.vue
<template lang="pug">
  #app
    nav
      router-link(to="/") Home
      router-link(to="/about") About
    router-view
</template>

<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
  sockets: {
    connect () {
      console.log('log from index.vue')
    }
  }
})
</script>

Консоль браузера
5e875557096d6240646780.png
  • Вопрос задан
  • 92 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы