Как устранить ошибку сборки socket.io возникующую при взаимодействии с nuxt/server?

Текст ошибки
i Waiting for file changes                                                                              10:24:54
(node:11052) UnhandledPromiseRejectionWarning: TypeError: socket_io_client__WEBPACK_IMPORTED_MODULE_2___default.a.on is not a function
    at on (C:\projects\js\nuxt-tmp\build\webpack:\server\index.js:24:6)
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:228:7)
(node:11052) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:11052) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.


Файл для взаимодействия с сервером через nuxt
import Koa from 'koa'
import { Nuxt, Builder } from 'nuxt'
import io from 'socket.io-client'
import rootRouter from './routes'

var server = async function() {
  const app = new Koa()
  const host = process.env.HOST || '127.0.0.1'
  const port = process.env.PORT || 3000

  // Import and Set Nuxt.js options
  const config = require('../nuxt.config.js')
  config.dev = !(app.env === 'production')

  // Instantiate nuxt.js
  const nuxt = new Nuxt(config)

  // Build in development
  if (config.dev) {
    const builder = new Builder(nuxt)
    await builder.build()
  }

  io.on('connection', client => {
    client.join('messages');
    client.on('message', req => {
        insertInto(req);
        io.to('messages').emit('message', req.message);
    });
  });
  
  app.use(rootRouter.routes()).use(ctx => {
    ctx.status = 200
    ctx.respond = false // Mark request as handled for Koa
    ctx.req.ctx = ctx // This might be useful later on, e.g. in nuxtServerInit or with nuxt-stash
    nuxt.render(ctx.req, ctx.res)
  })

  app.listen(port, host)
  console.log('Server listening on ' + host + ':' + port) // eslint-disable-line no-console
}

server()


Конфигурации nuxt
module.exports = {
  /*
  ** Headers of the page
  */
  head: {
    title: 'app title',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'description' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },
  /*
  ** Customize the progress bar color
  */
  loading: { color: '#ffffff' },

  css: [
    '~/node_modules/bootstrap/dist/css/bootstrap.min.css'
  ],

  modules: [
    '@nuxtjs/axios'
  ],
  /*
  ** Build configuration
  */
  build: {
    /*
    ** Run ESLint on save
    */
    extend (config, { isDev, isClient }) {
      if (isDev && isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        })
      }
    }
  }
}
  • Вопрос задан
  • 772 просмотра
Решения вопроса 2
rockon404
@rockon404
Frontend Developer
Не создаете экземпляр:
const socket = io('/path');

Вам тут надо использовать не socket.io-client, а socket.io.
Ответ написан
Комментировать
cimonlebedev
@cimonlebedev Автор вопроса
Пардон забыл передать server в io
import http from 'http'        
server = http.createServer(app.callback()),
        io = _io(server)
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

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

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