如何注册全局中间件
在 Socket.IO v2 中,为主命名空间注册的中间件将充当全局中间件,应用于所有命名空间,因为客户端将首先连接到主命名空间,然后连接到自定义命名空间。
// Socket.IO v2
io.use((socket, next) => {
// always triggered, even if the client tries to reach the custom namespace
next();
});
io.of("/my-custom-namespace").use((socket, next) => {
// triggered after the global middleware
next();
});
从 Socket.IO v3 开始,情况不再如此:附加到主命名空间的中间件仅在客户端尝试访问主命名空间时才会被调用。
// Socket.IO v3 and above
io.use((socket, next) => {
// only triggered when the client tries to reach the main namespace
next();
});
io.of("/my-custom-namespace").use((socket, next) => {
// only triggered when the client tries to reach this custom namespace
next();
});
要在较新版本中创建全局中间件,您需要将中间件附加到所有命名空间。
- 可以手动操作
const myGlobalMiddleware = (socket, next) => {
next();
}
io.use(myGlobalMiddleware);
io.of("/my-custom-namespace").use(myGlobalMiddleware);
- 或者使用
new_namespace
事件
const myGlobalMiddleware = (socket, next) => {
next();
}
io.use(myGlobalMiddleware);
io.on("new_namespace", (namespace) => {
namespace.use(myGlobalMiddleware);
});
// and then declare the namespaces
io.of("/my-custom-namespace");
注意
在 new_namespace
监听器之前注册的命名空间不会受到影响。
- 或者,在使用 动态命名空间 时,通过在父命名空间上注册中间件。
const myGlobalMiddleware = (socket, next) => {
next();
}
io.use(myGlobalMiddleware);
const parentNamespace = io.of(/^\/dynamic-\d+$/);
parentNamespace.use(myGlobalMiddleware);
注意
现有命名空间始终优先于动态命名空间。例如
io.of("/admin");
io.of(/.*/).use((socket, next) => {
// won't be called for the main namespace nor for the "/admin" namespace
next();
});
相关