简体   繁体   English

在 mydb.collection().find().toArray 回调中写入 re.send() function 是否无效?

[英]Is it invalid to write re.send() function inside mydb.collection().find().toArray callback?

I'am setting up a login page for my app.我正在为我的应用程序设置登录页面。 I want to send a file after verifing if the login page is provided with proper username and password.我想在验证登录页面是否提供正确的用户名和密码后发送文件。

I have a handler for a post request which checks if the user entered correct username and password.我有一个 post 请求的处理程序,它检查用户是否输入了正确的用户名和密码。

app.post('/login',function(req,res){
    var data="";
    var flag_isthere=0,wrongpass=0;
    console.log('login-done');
    req.setEncoding('UTF-8')
    req.on('data',function(chunk){
        data+=chunk;
    });
    req.on('end',function()
    {


        MongoClient.connect("mongodb://localhost:27017/userdetails",{useNewUrlParser: true ,useUnifiedTopology: true },function(err,db)
        {

            if(err) throw err;
            var q = JSON.parse(data)
            const mydb=db.db('userdetails')
            var c=mydb.collection('signup').find().toArray(
                function(err,res)
                {
                for(var i=0;i<res.length;i++)
                    if( (res[i].email==q['email']) )    //check if the account exists
                    {
                        flag_isthere=1;
                        if( (res[i].pass != q['pass'] ) )
                            wrongpass=1;
                        break;
                    }

                if(flag_isthere==0)
                {
                    console.log(q['email'], ' is not registered')
                }
                else
                {
                    console.log('Already exists!!!');       
                }

                if( wrongpass==1)
                {
                    console.log('password entered is wrong')
                }

                if(flag_isthere==1 && wrongpass==0)
                {
                    console.log('Congratulations,username and password is correct');
                    res.send( { login:'OK', error:'' } );    //this statement is giving an error in node JS part
                }


            });//var c
        })//mongoclient.connect

    })//req.on 

    res.send({ login:'OK', error:'' });     //this works properly in node JS
    console.log(flag_isthere , wrongpass )  //but here the flag_isthere==0 and wrongpass==0 , so it won't get validated

});

It gives the error as它给出的错误为

TypeError: res.send is not a function
    at E:\ITT_project_shiva\loginserver_new.js:112:25
    at result (E:\ITT_project_shiva\node_modules\mongodb\lib\operations\execute_operation.js:75:17)
    at executeCallback (E:\ITT_project_shiva\node_modules\mongodb\lib\operations\execute_operation.js:68:9)
    at handleCallback (E:\ITT_project_shiva\node_modules\mongodb\lib\utils.js:129:55)
    at cursor.close (E:\ITT_project_shiva\node_modules\mongodb\lib\operations\to_array.js:36:13)
    at handleCallback (E:\ITT_project_shiva\node_modules\mongodb\lib\utils.js:129:55)
    at completeClose (E:\ITT_project_shiva\node_modules\mongodb\lib\cursor.js:859:16)
    at Cursor.close (E:\ITT_project_shiva\node_modules\mongodb\lib\cursor.js:878:12)
    at cursor._next (E:\ITT_project_shiva\node_modules\mongodb\lib\operations\to_array.js:35:25)
    at handleCallback (E:\ITT_project_shiva\node_modules\mongodb\lib\core\cursor.js:32:5)
[nodemon] app crashed - waiting for file changes before starting...

How do I send the response to the user after proper validation?正确验证后如何将响应发送给用户?

It's not that you're doing it from the callback that's the problem.问题不是你是从回调中做的。 There are two different problems:有两个不同的问题:

  1. You're shadowing res by redefining it in the callback's parameter list您通过在回调的参数列表中重新定义它来隐藏res

  2. (Once you fix that) You're calling res.send twice : (一旦你解决了)你打电话res.send两次

    • Once at the end of your post handler一次在您的post处理程序结束时
    • Once within the callback一旦在回调中

    send implicitly completes the response, so you can only call it once. send隐式完成响应,因此您只能调用一次。

    In your case, you want to call it from within your callback, once you've determined that none of the records matches.在您的情况下,一旦您确定没有任何记录匹配,您想从回调中调用它。

See *** comments for a rough guideline (but keep reading):请参阅***评论以获得粗略的指导(但请继续阅读):

app.post('/login', function(req, res) {
    var data = "";
    var flag_isthere = 0,
        wrongpass = 0;
    console.log('login-done');
    req.setEncoding('UTF-8')
    req.on('data', function(chunk) {
        data += chunk;
    });
    req.on('end', function() {
        MongoClient.connect("mongodb://localhost:27017/userdetails", {
            useNewUrlParser: true,
            useUnifiedTopology: true
        }, function(err, db) {
            if (err) throw err;
            var q = JSON.parse(data)
            const mydb = db.db('userdetails')
            var c = mydb.collection('signup').find().toArray(
                function(err, array) { // *** Renamed `res` to `array
                    for (var i = 0; i < array.length; i++)
                        if ((array[i].email == q['email'])) //check if the account exists
                    {
                        flag_isthere = 1;
                        if ((array[i].pass != q['pass']))
                            wrongpass = 1;
                        break;
                    }

                    if (flag_isthere == 0) {
                        console.log(q['email'], ' is not registered')
                    } else {
                        console.log('Already exists!!!');
                    }

                    // *** Handle result here
                    if (flag_isthere == 1 && wrongpass == 0) {
                        console.log('Congratulations,username and password is correct');
                        res.send({ login: 'OK', error: '' }); //this statement is giving an error in node JS part
                    } else if (wrongpass == 1) {
                        console.log('password entered is wrong')
                        // *** res.send(/*...*/)
                    } else {
                        // Handle the issue that there was no match
                        // *** res.send(/*...*/)
                    }
                }
            ); //var c
        }) //mongoclient.connect
    }) //req.on 

    // *** Don't try to send a response here, you don't know the answer yet
});

but , it seems like you should be able to find just the one user (via findOne ? I don't do MongoDB), rather than finding all of them and then looping through the resulting array.但是,您似乎应该只能找到一个用户(通过findOne ?我不做 MongoDB),而不是找到所有用户,然后遍历结果数组。


See also the answers to these two questions, which may help you with asynchronous code issues:另请参阅这两个问题的答案,这可能会帮助您解决异步代码问题:


A couple of other notes:其他几点注意事项:

  1. I strongly recommend using booleans for flags, not numbers.我强烈建议对标志使用布尔值,而不是数字。

  2. NEVER store actual passwords in your database,.切勿在数据库中存储实际密码。 Store a strong hash, and then compare hashes.存储一个强哈希,然后比较哈希。

  3. You might find async / await syntax more convenient to work with.您可能会发现使用async / await语法更方便。 I think recent MongoDB clients support promises (which you need for async / await ).我认为最近的 MongoDB 客户端支持承诺(您需要async / await )。

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

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