javascript - 在 mydb.collection().find().toArray 回调中编写 re.send() 函数是否无效?

标签 javascript node.js mongodb xmlhttprequest nodemon

我正在为我的应用程序设置登录页面。我想在验证登录页面是否提供了正确的用户名和密码后发送文件。

我有一个用于发布请求的处理程序,它检查用户是否输入了正确的用户名和密码。

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

});

它给出的错误为

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...

正确验证后如何将响应发送给用户?

最佳答案

问题不在于您是通过回调执行此操作。有两个不同的问题:

  1. 您通过在回调的参数列表中重新定义 res 来隐藏它

  2. (一旦解决了这个问题)您将调用 res.send 两次:

    • post处理程序结束时
    • 一旦进入回调

    send 隐式完成响应,因此您只能调用一次。

    就您而言,一旦确定没有任何记录匹配,您希望从回调中调用它。

请参阅 *** 注释以获取粗略指南(但请继续阅读):

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
});

但是,看来您应该能够仅找到一个用户(通过 findOne ?我不使用 MongoDB),而不是找到所有其中,然后循环遍历结果数组。

<小时/>

另请参阅这两个问题的答案,这可能会帮助您解决异步代码问题:

<小时/>

其他一些注意事项:

  1. 我强烈建议使用 bool 值作为标志,而不是数字。

  2. 永远不要将实际密码存储在您的数据库中!存储一个强哈希,然后比较哈希。

  3. 您可能会发现 async/await 语法使用起来更方便。我认为最近的 MongoDB 客户端支持 Promise(您需要 async/await)。

关于javascript - 在 mydb.collection().find().toArray 回调中编写 re.send() 函数是否无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58659662/

相关文章:

javascript - 使用 AngularJS 开发完整的面向公众的企业应用程序

javascript - 如何停止浏览器建议字段输入?

javascript - 在页面 'www.foo.com' 上,从 'www.example.com' 加载的脚本可以向 'www.example.com' 发送 ajax 请求吗?

node.js - JSON Web token (JWT) 安全性

mongodb - 在 mongodb 上查找最小值

javascript - 将 javascript 插入多个现有页面的最佳选择

javascript - 如何注销 ipcRenderer.on 事件监听器?

javascript - 如果代码需要很长时间才能完成,如何在 node.js 中引发超时错误?

php - 使用 MongoDate 与 UTCDateTime 进行查询

javascript - 没有显示数据库内容(Meteor、AngularJS、mongodb)