node.js - 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 是一个函数,有人可以解释一下并帮我解决这个错误吗?
解决方案
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 ofverify.authSocket
is not a functionTypeError: verify.authSocket(...).on is not a function
indicates that the returned value ofverify.authSocket
doesn't have an.on
property which is a functionTypeError: verify.authSocket is not a function
indicates thatverify.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);
});
});
推荐阅读
- javascript - this.router.routeReuseStrategy.shouldReuseRoute = () => false;
- c - 如何在循环中制作变量表?
- vue.js - 页面上样式验证元素的问题
- c# - 我可以将 ASP.NET Core MVC 添加到现有的 ASP.NET Web 窗体应用程序吗
- android - React Native - 我想导入 2 个同名的组件
- java - 如何使用 fhir API 解析 ClinicalDocument 响应
- python - 是否可以使用 python 从交互式 JS 图中提取数据?
- r - 如何对函数的每个参数连续应用相同的更改?
- django-email - 如何从 .env 中读取 django 项目的 settings.py 文件?
- javascript - 在javascript中的then/catch之前执行一个函数(例如finally)