简体   繁体   English

使用 express 出错:发送标头后无法设置标头

[英]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.我正在创建 express 应用程序,并在路由器中从 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当我运行代码并在浏览器中打开一个 url 时,它在控制台上给我错误说明

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.我知道错误是因为我在函数中渲染 res 两次,但不知道如何克服这种情况。

Since the db calls are async, you need to make sure they're both done before rendering the response.由于 db 调用是异步的,因此在呈现响应之前,您需要确保它们都已完成。 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来源:使用 Express 和 MongoDB 从多个单独的集合中获取

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM