我正在将NextJS与Socket.IO一起使用。所有的基础知识都运作良好,现在,我正在尝试使用emit的函数进行确认回调。我已经遵循了所有规则,但这是行不通的。我不知道为什么。
这是我的server.js代码段:
// listen for socket's connection
io.sockets.on("connection", (socket)=>{
// socket.join('some room');
// on connection, listen any event on join's channel
socket.on('join',(param, callback) => {
console.log("callback: ", callback)
// some logs to appreciate if my URL's params follow the rules
console.log("!isRealString(param.name): ", !isRealString(param.name) )
console.log(" !isRealString(param.room): ", !isRealString(param.room))
// if they fails to follow the rules, return an error
if(!isRealString(param.name) || !isRealString(param.room)){
callback("Name and room are required") // not a function
}
// if no error, returns a succeed's log -set in client side-
callback()
});
我的客户方摘要:
// set socket.io variable
this.socket=io();
// on connect, trigger a function
this.socket.on("connect", () => {
// get the window's URL
// and pass an helper which translate URL's queries in javascript's object
var param =deparam(window.location.search);
// then emit an event on joint channel
// three parameters: channel, param, acknowledgement callback
this.socket.emit("join", param, function(err){
// if there is an error, alert the user then redirect
if(err){
alert(err);
Router.replace("/");
}
// errorFree? display a succeed's message
else{
console.log("No error");
}
});
});
如果我相信自己做过的谷歌搜索,那么一切似乎都很好。也许是NextJS有一些古怪的行为, 任何提示都会很棒, 谢谢
答案 0 :(得分:0)
窗口对象不会总是在下一个js中定义,但是您可以通过使用以下命令检查其SSR:
process.browser
在调用window.location之前避免错误