vue客户端套接字未连接到服务器

时间:2019-06-22 13:08:58

标签: node.js express vue.js socket.io

我正在尝试使用App.vueserver.js中的套接字并启动socket.io连接。但是,我从浏览器中收到以下错误。在我的server.js文件中,我看到console.log(socket.id)无法正常工作,但是在端口$ {port} console.log(上运行的)服务器可以正常工作。谁能告诉我我做错了什么?

错误消息

enter image description here

App.js

<template>
  <v-app app>

    <v-toolbar dense fixed>
      <v-toolbar-title color="purple darken-1">
        <img id="byron_logo" :src="require(`@/assets/byron_logo.png`)">
      </v-toolbar-title>

      <v-spacer></v-spacer>

      <v-btn icon>
        <router-link to="/"><v-icon color="red darken-1">assignment_ind</v-icon></router-link>
      </v-btn>

      <v-btn icon>
        <router-link to="/metrics"><v-icon color="blue darken-1">insert_chart_outlined</v-icon></router-link>
      </v-btn>

      <v-btn icon>
        <router-link to="/dog"><v-icon color="blue-grey darken-1">fas fa-dog</v-icon></router-link>
      </v-btn>
    </v-toolbar>

    <v-content class="main-content">
      <router-view/>
    </v-content>

  </v-app>
</template>

<script>
import io from 'socket.io-client'
var socket = io.connect('http://localhost:8081');

export default {
  name: 'App',
  components: {},
  data () {
    return {

    }
  },
  created () {
    socket.emit('SEND_MESSAGE', {
        user: 'Client',
        message: 'App.vue to server.js'
    })
  },
  mounted () {

  }
}
</script>

<style scoped>
  #byron_logo{
    display: flex;
    width: 6rem;
  }
  .main-content{
    margin-top: 5rem;
  }
  a{
    color: transparent !important;
    background-color: transparent !important;
  }
</style>

server.js

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const port = process.env.PORT || 1991


const app = express()

// middleware
app.use(cors())

// routes
const metrics = require('./routes/api/metrics') 
app.use('/api/metrics', metrics)

// run server
const server = app.listen(port, ()=>{
    console.log(`server running on port ${port}`)
})

// socket.io instance
const io = require('socket.io')(server)

// socket.io connection
io.on('connection', (socket) => {
    console.log(socket.id)
    socket.on('SEND_MESSAGE', function(data) {
        io.emit('MESSAGE', data)
        console.log(data)
    });
})

0 个答案:

没有答案