首页 > 解决方案 > node js/socket/verify不是函数

问题描述

您好想了解导致此错误的原因:不是函数(我错过了使它发生的原因)

我试图通过连接我的 io 套接字来验证我的 jwt:

  io.use(verify.authSocket(socket)
  .on('connection', function(socket) {
      socket.on('message', function(message) {
          io.emit('message', message);
      });
  }));

这是 mt verify.authSocket:

const jwt = require('jsonwebtoken');
const User = require('../models/User')
const config= require('../config/dbconfig');
const moment = require('moment');

module.exports = {
    async authSocket(socket,next){
        const token = socket.handshake.query.token;
        if(!token) return next(new Error('Unauthorized'));
        try{
            const decoded = jwt.verify(token,config.secretToken);
            if(decoded){    
                next();
            }else{
                next(new Error('Authentication error')); 
            }
        }catch(error){
            console.error(error);
        }
    }
}

错误:

C:\Users\SpiriT\Documents\Projetos\FtcJokenPo\back\src\app.js:25
  .on('connection', function(socket) {
   ^

TypeError: verify.authSocket(...).on is not a function
    at Object.<anonymous> (C:\Users\SpiriT\Documents\Projetos\FtcJokenPo\back\src\app.js:25:4)

我试图了解导致此错误的原因

我以为我的 verify.authsocket 是一个函数,有人可以解释一下并帮我解决这个错误吗?

标签: node.jssocket.io

解决方案


verify.authSocket is indeed a function. The error is telling you that the returned value from verify.authSocket is not a function, hence the (...) in the error message

 io.use(verify.authSocket(socket)) // added )
  .on('connection', function(socket) {
      socket.on('message', function(message) {
          io.emit('message', message);
      });
  });

In your code you were attaching .on to the return value of verify.authSocket instead of adding it to io

Have in mind that while the errors are similar, they're not the same:

  • TypeError: verify.authSocket(...) is not a function indicates that the returned value of verify.authSocket is not a function
  • TypeError: verify.authSocket(...).on is not a function indicates that the returned value of verify.authSocket doesn't have an .on property which is a function
  • TypeError: verify.authSocket is not a function indicates that verify.authSocket is not a function

In any case, io.use expects a function as argument, and you're not passing one. verify.authSocket must return a valid middleware or just be one.

So just use: verify.authSocket instead of verify.authSocket(socket)

io.use(verify.authSocket)
  .on('connection', function(socket) {
      socket.on('message', function(message) {
          io.emit('message', message);
      });
  });

推荐阅读