简体   繁体   中英

Getting Error with express : Can't set headers after they are sent

I am creating express app and in the router I am going to fetch data from the mongodb. here is my code

router.get('/', function(req, res, next) {
    MongoClient.connect(url, function(err, db) {
    db.collection('school').find({}).toArray(function(err, doc) {
          assert.equal(null, err);
          assert.ok(doc != null);
          res.render('index', { title: 'iGyan.org', schools: doc});
        });

    db.collection('students').find({}).toArray(function(err, doc) {
          assert.equal(null, err);
          assert.ok(doc != null);
          res.render('index', { title: 'iGyan.org',students: doc});
        });
    db.close();
});
});

When I run the code and opens a url in browser, it gives me error on the console stating

Error: Can't set headers after they are sent.

I have seen almost all suggested question asked on stack overflow, but cant get help out of it.

I know the error is because I am rendering the res two time in the function but do not know how to overcome the situation.

Since the db calls are async, you need to make sure they're both done before rendering the response. Based on that answer , you could use the async lib to accomplish this.

You could render the response only once like this:

router.get('/', function(req, res, next) {

    MongoClient.connect(url, function(err, db) {
        var data = {};
        var tasks = [
            // Load users
            function(callback) {
                db.collection('school').find({}).toArray(function(err, doc) {
                    if (err) return callback(err);
                    data.schools = doc;
                    callback();
                });
            },
            // Load colors
            function(callback) {
                db.collection('students').find({}).toArray(function(err, doc) {
                    if (err) return callback(err);
                    data.students: doc;
                    callback();
                });
            }
        ];

        //This function gets called after the two tasks have called their "task callbacks"
        async.parallel(tasks, function(err) {
            //If an error occurred, let express handle it by calling the `next` function
            if (err) return next(err);
            db.close();
            res.render('index', {
                title: 'iGyan.org',
                students: data.students,
                schools: data.schools
            });
        });
    });

});

Source: Fetch from multiple, separate, collections with Express and MongoDB

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