Saturday 29 April 2017

How to handle "post" request in node.js in a one-page web app

I know there are a few answers matching this question already. But I am looking for something else.

In the client side I have a signUp form that will send a post request to the server with username and password.

In the server side I authenticate the request. This is the code. (I use express)

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
        }
    };

At this stage I don't want to make another webpage(like/signup) to handle the signUp event.

I can access the client's socket id if I put the above code under the io.sockets.on code.

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"?
        }
    };

In the server.post handler, I dont want to use any method like res.send,res.redirect(newURL) as I want the client side to stay at the same page. So is there a way to communicate with client side in the "post" handler like client emit?



via Wei Zheng

No comments:

Post a Comment