NuxtJS Socket.io 无法在生产环境中工作

NuxtJS Socket.io not working in production

我正在尝试在 NuxtJS SSR 应用程序中使用 socket.io。但不幸的是它只适用于开发。一旦我构建并开始生产,它就不再起作用了。我尝试了多种方法(最后解释),并且我总是得到相同的输出。这个版本,使用 nuxt hooks,是最干净的,在开发上运行良好。

这是我的服务器端模块 (modules/ws.js) :

import socketIO from 'socket.io'

export default function () {
  this.nuxt.hook('listen', (server, { host, port }) => {
    console.log(`ListentHook : Listening on http://${host}:${port}`)
    const io = socketIO(server)

    io.on('connection', (ws) => {
      console.log('Client connected')
      ws.on('message', (message) => {
        console.log('received: %s', message)
      })
      ws.emit('message', 'Hello new client')
    })
  })
}

客户端,我有一个插件(plugins/socket.io.js) :

import io from 'socket.io-client'

const socket = io('http://localhost:3000')

export default socket

在我的 vue 上,我导入客户端套接字并监听消息 (pages/index.vue) :

<script>
import socket from '~/plugins/socket.io.js'

export default {
  name: 'Index',
  beforeMount () {
    socket.on('message', this.printMsg)
  },
  methods: {
    printMsg (msg) {
      console.log(msg)
    }
  }
}
</script>

这是我的 nuxt.config.js 文件:

...
  buildModules: [
    '@nuxtjs/eslint-module',
    '@nuxtjs/tailwindcss',
    '~/modules/ws'
  ],
...

在开发模式下它工作得很好。 当我加载 http://localhost:3000 时,我得到:

"Client connected" on server side

"Hello new client" on client side

现在,当我构建应用程序时没有任何效果,我只在客户端控制台中收到错误消息:

GET http://localhost:3000/socket.io/?EIO=4&transport=polling&t=NSauEZA 404 (Not Found)

我真的不明白为什么。

我已经做了:

测试了官方的 nuxt with-sockets 示例: https://github.com/nuxt/nuxt.js/tree/dev/examples/with-sockets --> 结果相同(Nuxt 独立版)

查找并发布关于 gitHub 的问题: https://github.com/nuxt/nuxt.js/issues/6928 --> 相同的结果

测试放置.env变量 --> 相同的结果(并且工作环境变量改变了实际的服务器端口)

感谢您的帮助!! 如果需要,我可以提供更多代码!

您的模块是 运行 WS 的服务器中间件,因此您必须在 nuxt.config.js 文件的 modules 数组中而不是 buildModules 中声明它数组,在生产中为 运行。

Nuxt documentation 中所述,buildModules 仅在开发和构建期间使用。