简体   繁体   English

我的nodejs代码中有错误

[英]Error in my nodejs code

I am writing this code as a project for a customer and when i go to a show route i got this 500 internal server error 我正在为客户的项目编写此代码,当我走秀路线时,收到此500内部服务器错误

http.get('/files/:id', function(req, res) {
    var vid;
    var pap;
    Videos.find({}, function(err, videos) {
        if (err) {
            console.log(err);
        } else {
            vid = videos;
        }
    });

    Papers.find({}, function(err, file) {
        if (err) {
            console.log(err);
        } else {
            pap = file;
        }
    });

    Material.findById(req.params.id, function(err, found) {
        if (err) {
            console.log(err);
        } else {
            res.render('files', {
                file: pap,
                video: vid,
                current: found
            });
        }
    });
});

this is my show route code. 这是我的表演路线代码。

Note : if i reload the page the error is gone and the page open. 注意 :如果我重新加载页面,错误将消失并且页面将打开。

The reason is you need to wait for all the database queries to finish before rendering. 原因是您需要等待所有数据库查询完成后再呈现。 In your code, it is possible for the page to render before the other two queries have completed and returned their data. 在您的代码中,页面有可能在其他两个查询完成并返回其数据之前呈现。 The good news is that Mongoose supports Promises for asynchronous functions. 好消息是, Mongoose支持异步功能的Promises

http.get('/files/:id', function(req, res) {
    Promise.all([
        Videos.find({}).exec(),
        Papers.find({}).exec(),
        Material.findById(req.params.id).exec()
    ]).then( ([video, paper, material]) => {
        res.render('files', {
            file: paper,
            video: video,
            current: material
        });
    }).catch( error => console.log(error) );
});

The functions you're using with Mongoose are asynchronous in nature; 您在Mongoose上使用的功能本质上是异步的。 the variables vid and pap are not initialized when you run res.render . 运行res.render时,变量vidpap没有初始化。 When you attempt to use those variables in your frontend (template like Jade, Handlebars EJS, I don't know what you're using), they are undefined, and subsequently cause the 500 error. 当您尝试在前端中使用这些变量(如Jade,Handlebars EJS之类的模板,我不知道您在使用什么)时,它们是未定义的,并随后导致500错误。 You'll need to run the functions such that the results of all Mongoose queries are available to res.render when it runs; 您需要运行这些函数,以便所有Mongoose查询的结果在运行时都可用于res.render either using an async NodeJS library, or calling each function within one another and then calling res.render at the end. 使用异步NodeJS库或在彼此内部调用每个函数,然后最后调用res.render。

Solution 1: Using async Node module 解决方案1:使用async节点模块

var async = require('async');
async.parallel([
    // Each function in this array will execute in parallel
    // The callback function is executed once all functions in the array complete
    function (cb) {
        Videos.find({}, function(err, videos) {
            if (err) {
                return cb(err);
            } else {
                return cb(null, videos);
            }
        });
    },
    function (cb) {
        Papers.find({}, function(err, papers) {
            if (err) {
                return cb(err);
            } else {
                return cb(null, papers);
            }
        });
    },
    function (cb) {
        Material.findById(req.params.id, function(err, found) {
            if (err) {
                return cb(err);
            } else {
                return cb(null, found);
            }
        });
    }
], function (err, results) {
    if (err) {
        // If any function returns an error
        // (first argument), it will be here
        console.log(err);
    }
    else {
        // Even though the functions complete asynchronously,
        // the order in which they are declared in the array
        // will correspond to the position in the array
        // if it returns anything as a second argument.
        var videos = results[0];
        var files  = results[1];
        var found  = results[2];
        res.render('files', {
            file: files,
            video: videos,
            current: found
        });
    }
});

Solution 2: Nested Callbacks 解决方案2:嵌套的回调

Videos.find({}, function(err, videos) {
    var vid = videos;
    if (err) {
        console.log(err);
    } else {
        Papers.find({}, function(err, file) {
            var pap = file;
            if (err) {
                console.log(err);
            } else {
                Material.findById(req.params.id, function(err, found) {
                    if (err) {
                        console.log(err);
                    } else {
                        res.render('files', {
                            file: pap,
                            video: vid,
                            current: found
                        });
                    }
                });
            }
        });
    }
});

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

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