ExpressJS & Websocket & session sharing

后端 未结 5 1365
情书的邮戳
情书的邮戳 2020-12-01 09:30

I\'m trying to make a chat application based on Node.js. I\'d like to force websocket server (ws library) to using ExpressJS session system. Unfortunately, I\'ve got stuck.

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 09:59

    In version 3.2.0 of ws you have to do it a bit differently.

    There is a full working example of express session parsing in the ws repo, specifically using a new feature verifyClient.

    A very brief usage summary:

    const sessionParser = session({
      saveUninitialized: false,
      secret: '$eCuRiTy',
      resave: false
    })
    
    const server = http.createServer(app)
    const wss = new WebSocket.Server({
      verifyClient: (info, done) => {
        console.log('Parsing session from request...')
        sessionParser(info.req, {}, () => {
          console.log('Session is parsed!')
          done(info.req.session.userId)
        })
      },
      server
    })
    
    wss.on('connection', (ws, req) => {
      ws.on('message', (message) => {
        console.log(`WS message ${message} from user ${req.session.userId}`)
      })
    })
    

提交回复
热议问题