【问题标题】:NuxtJS Socket.io not working in productionNuxtJS Socket.io 无法在生产中工作
【发布时间】:2021-04-25 21:43:14
【问题描述】:

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

这是我的服务器端模块(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 我得到:

服务器端的“客户端已连接”

客户端的“Hello new client”

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

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

我真的不明白为什么。

我已经做过的事情:

测试了官方的 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 变量 --> 相同的结果(并且工作环境变量改变了实际的服务器端口)

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

【问题讨论】:

    标签: node.js socket.io nuxt.js server-side-rendering


    【解决方案1】:

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

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

    【讨论】:

    • 我测试了很多东西,解决方案非常简单明了......非常感谢!
    猜你喜欢
    • 2023-01-10
    • 2021-10-09
    • 2018-05-03
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多