nodejs socket.io套接字不是函数

问题描述 投票:0回答:1

我有一个中间件来通过jwt验证我的套接字但我在其他文件夹中创建新事件时遇到问题不把所有东西都放在我的app.js中

我这样做是为了验证我的套接字:

  let io = require('socket.io')(server);
  app.set("io", io);

  io.use(verify.passportJwtAuth);
  io.on('connection', function(socket) {
    console.log('Authentication passed!');
    // now you can access user info through socket.request.user
    // socket.request.user.logged_in will be set to true if the user was authenticated
    socket.emit('success', {
      message: 'success logged in!'
    });
  });

midd:

async passportJwtAuth(socket,next) {
    const secret =  config.jwt.secret;
    const token = socket.handshake.query.token;
    jwt.verify(token, secret, function(err, decoded) {
        if(err) {
            return next(err);
        }
        console.log("sucess");
        return next();
    });
} 

我尝试制作新的event

const socketRouter = require('./routes/socket');
  io.use(verify.passportJwtAuth);
  io.on('connection', function(socket) {
    console.log('Authentication passed!');
    // now you can access user info through socket.request.user
    // socket.request.user.logged_in will be set to true if the user was authenticated
    socket.emit('success', {
      message: 'success logged in!'
    });
  });
socketRouter.configuration();

我的socketRouter.configuration:

const socketController = require ('../controllers/SocketController');
const verify = require('../auth/index');
const socket = require('socket.io');
module.exports = {    
   configuration: () => {        
      socket.on ('message', (message) => {
         socket.emit ('myevent', {message: 'Ok, You are signed in'});
         console.log (message);
         console.log (`Socket $ {socket.id}`)
       });
   }
}

错误:

C:\Users\SpiriT\Documents\Projetos\FtcJokenPo\back\src\routes\socket.js:6
      socket.on ('message', (message) => {
             ^

TypeError: socket.on is not a function
    at Object.configuration (C:\Users\SpiriT\Documents\Projetos\FtcJokenPo\back\src\routes\socket.js:6:14)
    at Object.<anonymous> (C:\Users\SpiriT\Documents\Projetos\FtcJokenPo\back\src\app.js:36:14)

我不想将我所有的套接字逻辑留在我的app.js中

也这样,当我打开服务器时,我已经调用了这个模块(我希望它仅在前端使用socket.on时才调用]]

有人可以帮我吗?

我的前端:

verify = () => {
    let socket = null;
    var token = 312312312;
    socket = io('http://localhost:8080', {
    query: {token: token}
    });
    socket.on('error', function(err) {
       console.error(err);
      });
      // Connection succeeded
      socket.on('success', function(data) {
        console.log(data.message);
      })
}

我有一个中间件通过jwt验证我的套接字,但是我在其他文件夹中创建新事件时遇到了问题,无法在我的app.js中获取所有内容,我这样做是为了验证我的套接字:let io = require('...] >

node.js socket.io
1个回答
0
投票

您没有确切显示什么文件中有什么代码,也没有显示从其他模块中导入东西的方式,因此很难为您提供确切的说明。

但是,关于socket.io io实例的一般想法是,您在一个文件中创建它,然后必须与需要它的任何其他模块/文件共享它。您决定如何共享它取决于您。

© www.soinside.com 2019 - 2024. All rights reserved.