如何注册全局中间件
¥How to register a global middleware
在 Socket.IO v2 中,为主命名空间注册的中间件将充当全局中间件,应用于所有命名空间,因为客户端将首先连接到主命名空间,然后连接到自定义命名空间:
¥In Socket.IO v2, a middleware that was registered for the main namespace would act as a global middleware, applying to all namespaces, since a client would first connect to the main namespace, and then to the custom namespace:
// 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 开始,情况不再如此:仅当客户端尝试访问主命名空间时才会调用附加到主命名空间的中间件:
¥This is not the case any more starting with Socket.IO v3: a middleware attached to the main namespace is only called when a client tries to reach the main namespace:
// 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();
});
要在较新版本中创建全局中间件,你需要将中间件附加到所有命名空间:
¥To create a global middleware in newer versions, you need to attach your middleware to all namespaces:
手动:
¥either manually:
const myGlobalMiddleware = (socket, next) => {
next();
}
io.use(myGlobalMiddleware);
io.of("/my-custom-namespace").use(myGlobalMiddleware);
或使用
new_namespace
事件:¥or by using the
new_namespace
event:
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
监听器之前注册的命名空间不会受到影响。
¥The namespaces that are registered before the new_namespace
listener won't be affected.
或者,当使用 动态命名空间 时,通过在父命名空间上注册中间件:
¥or, when using dynamic namespaces, by registering a middleware on the parent namespace:
const myGlobalMiddleware = (socket, next) => {
next();
}
io.use(myGlobalMiddleware);
const parentNamespace = io.of(/^\/dynamic-\d+$/);
parentNamespace.use(myGlobalMiddleware);
现有命名空间始终优先于动态命名空间。例如:
¥Existing namespaces always have priority over dynamic namespaces. For example:
io.of("/admin");
io.of(/.*/).use((socket, next) => {
// won't be called for the main namespace nor for the "/admin" namespace
next();
});
有关的:
¥Related: