错误ServerMiddleware应该公开句柄nuxt

时间:2020-08-23 13:43:30

标签: websocket nuxt.js ws

  • 新的nuxt.js设置没有服务器文件夹
  • 您创建一个API文件夹,并在其中放置一个文件以暴露服务器
  • 我正在尝试通过ws库使用websocket来分析用户会话并收到此错误

这是我放置在api文件夹中的app.js代码

import http from 'http'
import logger from 'express-pino-logger'
import express from 'express'
import cookieParser from 'cookie-parser'
import WebSocket from 'ws'
const app = express()
const sessionParser = cookieParser()
const map = new Map()
app.use(logger())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
app.use(sessionParser)
app.use('/v1', (req, res) => res.json('hello'))

const server = http.createServer(app)
const wss = new WebSocket.Server({ noServer: true })

wss.on('connection', function connection(ws, request, client) {
  ws.on('message', function message(msg) {
    console.log(`Received message ${msg} from user ${client}`)
  })
})

server.on('upgrade', function (request, socket, head) {
  console.log('Parsing session from request...')

  sessionParser(request, {}, () => {
    if (!request.session.userId) {
      socket.destroy()
      return
    }

    console.log('Session is parsed!')

    wss.handleUpgrade(request, socket, head, function (ws) {
      wss.emit('connection', ws, request)
    })
  })
})

wss.on('connection', function (ws, request) {
  const userId = request.session.userId

  map.set(userId, ws)

  ws.on('message', function (message) {
    //
    // Here we can now use session parameters.
    //
    console.log(`Received message ${message} from user ${userId}`)
  })

  ws.on('close', function () {
    map.delete(userId)
  })
})

server.listen(3000)

export default server

我的nuxt.config.js文件

export default {
  /*
   ** Nuxt rendering mode
   ** See https://nuxtjs.org/api/configuration-mode
   */
  mode: 'universal',
  /*
   ** Nuxt target
   ** See https://nuxtjs.org/api/configuration-target
   */
  target: 'server',
  /*
   ** Headers of the page
   ** See https://nuxtjs.org/api/configuration-head
   */
  head: {
    title: process.env.npm_package_name || '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      {
        hid: 'description',
        name: 'description',
        content: process.env.npm_package_description || '',
      },
    ],
    link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],
  },
  /*
   ** Global CSS
   */
  css: [],
  /*
   ** Plugins to load before mounting the App
   ** https://nuxtjs.org/guide/plugins
   */
  plugins: [],
  /*
   ** Auto import components
   ** See https://nuxtjs.org/api/configuration-components
   */
  components: true,
  /*
   ** Nuxt.js dev-modules
   */
  buildModules: [
    // Doc: https://github.com/nuxt-community/eslint-module
    '@nuxtjs/eslint-module',
    // Doc: https://github.com/nuxt-community/stylelint-module
    '@nuxtjs/stylelint-module',
  ],
  /*
   ** Nuxt.js modules
   */
  modules: [
    // Doc: https://axios.nuxtjs.org/usage
    '@nuxtjs/axios',
    '@nuxtjs/pwa',
  ],
  /*
   ** Axios module configuration
   ** See https://axios.nuxtjs.org/options
   */
  axios: {},
  /*
   ** Build configuration
   ** See https://nuxtjs.org/api/configuration-build/
   */
  build: {},
  serverMiddleware: ['~/api/app'],
}

enter image description here

如何从app.js公开Websocket服务器?

1 个答案:

答案 0 :(得分:1)

您应该导出服务器中间件。在底部添加:

//导出服务器中间件 module.exports = { 路径:“ / api”, 处理程序:应用 }