简体   繁体   中英

NextJS, Socket.io: in the server-side, my third parameter which is a acknowledgement's callback returns to me: callback is not a function

I'm using NextJS with Socket.IO. All the basics works good, now, I'm trying to make acknowledgement callback with an emit's function. I have follow it seems to me all the rules, but it doesn't work. I can't figure why.

Here my server.js snippet:

// 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()      

});

my client's side snippet:

// 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");
      }
   });
});

It seems to me all is good if I believe the googling I have done. Maybe is NextJS who have some quirk behaviors, Any hint would be great, thanks

window object would not always be defined in next js, but you can check if its SSR by using

  process.browser

before calling window.location to avoid error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM