Sé que ya hay algunas respuestas que coinciden con esta pregunta. Pero estoy buscando algo más.
En el lado del cliente, tengo un formulario de registro que enviará una solicitud de post al servidor con nombre de username y password .
En el lado del servidor, autentico la solicitud. Este es el código. (Yo uso expreso)
server.post('/', function(req, res) { res.redirect('/');// I want to get rid of the "confirm resubmission message upon refreshing the page" authenticate(req.body.username){ if(false){ client.emit('signUpResponse',{success:false}); //cannot do it without a client's socket id } else { db.user.insert({username:req.body.username}) client.emit('signUpResponse',{success:true}); //cannot do it without a client's socket id } };En esta etapa, no quiero crear otra página web (me gusta/registrarse) para manejar el evento de registro.
Puedo acceder a la identificación del socket del cliente si coloco el código anterior debajo del código io.sockets.on .
io.sockets.on('connection', function (client) { server.post('/', function(req, res) { console.log(client.id) //now I can access the client's socket res.redirect('/');// I want to get rid of the "confirm resubmission message upon refreshing the page" authenticate(req.body.username){ if(false){ client.emit('signUpResponse',{success:false}); //nothing happens at the client' side. maybe something to do with the "res.redirect"? } else { db.user.insert({username:req.body.username}) client.emit('signUpResponse',{success:true}); ////nothing happens at the client' side. maybe something to do with the "res.redirect"? } }; En el controlador server.post , no quiero usar ningún método como res.send , res.redirect(newURL) ya que quiero que el lado del cliente permanezca en la misma página. Entonces, ¿hay alguna forma de comunicarse con el lado del cliente en el controlador de "publicación" como la emisión del client emit ?
Supongo que el sitio está usando https. Dicho esto, deberías usar socket.io. Es mucho más fácil.
// On the client-side var client = io(); client.on('userLoggedIn', function(confirm) { if (confirm) { // Do your post login confirmation stuff here } }); var form = document.getElementById('login-form'), username = document.getElementById('username').value, password = document.getElementById('password').value; form.addEventListener('submit', function(event) { client.emit('login', { username: username, password: password }); // Stops the form from redirecting the web page to the action link event.preventDefault(); }, false); // Server-side io.on('connection', function(client) { // Login user client.on('login', function(user) { // Do your login stuff here }); });