0

I am using nodejs express and firebase for my database. So what I am trying to do is upon user's post request, update firebase data and redirect user to another page. But I keep getting Error: Can't set headers after they are sent.

Here is my code in controller.js file:

app.post('/carpark', urlencodedParser, function(req,res){
    req.session.carpark = req.body.carpark;  
lotsRef.orderByChild('CarparkName').equalTo(req.session.carpark).on('value', function(snapshot){
        for (var key in snapshot.val()) {
            if (snapshot.val()[key]['Availability'] == true) {
                firebase.database().ref('Lots/'+ key).update({'Availability': false });
                res.redirect('checkin');           
                break;
            }
        }
    });

EDITED:

app.post('/carpark', urlencodedParser, function(req,res){
    req.session.carpark = req.body.carpark;
    lotsRef.orderByChild('CarparkName').equalTo(req.session.carpark).on('value', function(snapshot){
        for (var key in snapshot.val()) {
            var allocatedtime = new Date().getHours() + ':' + (new Date().getMinutes() <10 ? '0' : '') + new Date().getMinutes() + ':' + (new Date().getSeconds() <10 ?'0' : '') + new Date().getSeconds();
                req.session.key = key;
                req.session.LotID = snapshot.val()[key]['LotID'];
                req.session.AllocatedTime = allocatedtime;
                req.session.SerialNum = snapshot.val()[key]['SerialNumber'];
                var date = new Date().getFullYear() + "-" + (new Date().getMonth()+1) + "-" + new Date().getDate();
                req.session.DateAllocated = date;
                console.log(req.session);
                firebase.database().ref('Lots/'+ req.session.key).update({'Availability': false });
                break;
            }
        }
        res.redirect('checkin'); 
    });
KENdi
  • 7,576
  • 2
  • 16
  • 31
  • 1
    Hey, `res.redirect('checkin'); ` this statement can't go in for loop. Or else you can try return from there. – krish Nov 14 '17 at 05:34
  • Hi thanks, but the reason I put it there is because I am storing values of the snapshot into a session (which I omitted here). If i move the redirect statement out, then the session wont store anything which I have no idea why... but would it matter though because I would break out of the loop once the if statement is fulfilled? – user8806671 Nov 14 '17 at 06:15
  • We need to see your omission. You may want to refer this for a better understanding of reason for error https://stackoverflow.com/a/7086621/6165688 I guess you are trying to store something in req.session at the wrong place – divsingh Nov 14 '17 at 06:47
  • @divsingh I have edited and added my full code accordingly – user8806671 Nov 14 '17 at 06:56
  • @user8806671 i can see that you no longer have the if clause. Do you want to set all the snapshots in session? If so, then you are not doing it correct. – divsingh Nov 14 '17 at 07:21
  • @user8806671 It is better to use async for such conditions where you have to iterate over an array, make a blocking call like database update for each item and return an aggregated response. Refer https://caolan.github.io/async/docs.html#map – divsingh Nov 14 '17 at 07:30
  • @divsingh yes I am trying to set the snapshots in session. I am new to this so I am not sure with how things should be like. – user8806671 Nov 14 '17 at 07:50

1 Answers1

0

The redirect should be moved outside For loop:

app.post('/carpark', urlencodedParser, function(req,res){
    req.session.carpark = req.body.carpark;  
lotsRef.orderByChild('CarparkName').equalTo(req.session.carpark).on('value', function(snapshot){
        for (var key in snapshot.val()) {
            if (snapshot.val()[key]['Availability'] == true) {
                firebase.database().ref('Lots/'+ key).update({'Availability': false });         
                break;
            }
        }
        res.redirect('checkin');  
    });

But this will redirect to 'checkin' irrespective of your if clause, so that depends on your scenario whether you want to redirect to some other page when the if clause is not true even once.

divsingh
  • 1,172
  • 8
  • 15