简体   繁体   中英

NodeJS Express Routing with FireBase: Cannot set headers after they are sent to the client

I am trying a simple FireBase and NodeJS-Express Routing app. The problem I am facing is that when I send a POST after GET request, my NodeJS backend creates the record on the Firebase Backend, but after that it crashes, stating that "Cannot set headers after they are sent to the client".

The functions are:

/* GET all existing groups listing. */
router.get('/', function (req, res, next) {
    var db = admin.database();
    var dataToShow = [];
    var source = req.query.source;
    var destination = req.query.destination;
    var groupsListing = db.ref(url).orderByChild('source').equalTo(source);
    groupsListing.on('value', function(snapshot) {
        snapshot.forEach(function(childSnapshot){
            var childKey = childSnapshot.key;
            var childData = childSnapshot.val();
            if(childData.destination == destination) {
                dataToShow.push(childData);
            }
        });
        return res.status(200).json(dataToShow);
    });
});

/* POST a new group listing. */
router.post('/', function (req, res, next) {
    var db = admin.database();
    var newKey = db.ref(url).push().key;
    var groupData = {
        key: newKey,
        source: req.body.source,
        destination: req.body.destination,
        time: req.body.time,
    };
    db.ref(url + newKey).update(groupData, function () {
        return res.send("Added");
    });
});

I am unable to understand why it isn't working, because I cant see if multiple res is being sent from anywhere. I have tried a couple of other things like returning JSON objects. But that didn't really help. My simple queries through POSTMAN fail.

Any help on this would be highly appreciated.

I think that your groupList.on is executed many times. It is probabily that your code execute thw content inside of the 'groupList.on' for many times.

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