如何註冊全域中介軟體
在 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();
});
相關