如何将中间件绑定到socket.io中的事件 [英] how to bind middleware to events in socket.io
本文介绍了如何将中间件绑定到socket.io中的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
现在,您可以将中间件绑定到 io.use(中间件);
,但只有在建立套接字连接时才会触发此操作。有没有办法在将它传递给像expressjs这样的事件句柄之前拦截它?
Right now you can bind middleware to io.use(middleware);
, but this is triggered only when a socket connection is made. Is there a way to intercept it before passing it to an event handle like in expressjs?
换句话说....
在 express.js 中你可以这样做:
app.get('/', middleware1, middleware2, function(req, res){
res.end();
});
我可以在 socket.io 中执行相同操作吗?
Can I do the same in socket.io?
socket.on('someEvent', middleware1, middleware2, function(data){
console.log(data); // data is now filtered by 2 previous middlewares
});
推荐答案
从Socket.io v2.0.4开始(发现这个在检查这个时,您可以像这样使用套接字中间件:
As of Socket.io v2.0.4 (found this while inspecting this) you can use a socket middleware like so:
io.on('connection', (socket) => {
socket.use((packet, next) => {
// Handler
next();
});
});
这意味着您可以像这样设置代码:
Which means that you can set your code like so:
io.on('connection', (socket) => {
socket.use((packet,next) => {
if (packet[0] === 'someEvent') {
if (authorizationCondition) {
return next(new Error('nope'))
}
}
next();
})
socket.on('someEvent', function(data){
console.log(data);
});
})
然后您可以通过客户端捕获这样的错误 - 支持
You will then be able to catch errors like this with a client-side
io.on('error', err => { ... }) // err will equal "nope"
这篇关于如何将中间件绑定到socket.io中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文