首页 > 解决方案 > 执行mongodb请求后如何向前端发送响应?

问题描述

我正在创建注册页面。在哪里,我首先检查用户电子邮件是否已经存在于我们的 mongodb 数据库中。如果它存在,那么我想向前端发送错误消息。但是,我没有这样做,我认为这可能是因为 JavaScript 的异步行为。我的代码如下:

var myObj , myJSON
var SignUpUserEmail, SignUpUserPassword, SignUpUserName, SignUpErr
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  var q = url.parse(req.url, true).query 
  SignUpUserEmail = q.SignUpUserEmail
  SignUpUserPassword = q.SignUpUserPassword
  SignUpUserName = q.SignUpUserName

  MongoClient.connect("mongodb://localhost:27017/ABC",function(err, 
  database) {
    if (err) throw err;
    var db=database.db('ABC')

    let findOneParam = {"UserEmail":SignUpUserEmail} 
    db.collection('Profiles').findOne(findOneParam, function(err, result) {
    if (err) throw err;
    if(!result) {
      db.collection('Profiles', function(err, collection){
        if (err) throw err;
        collection.insertOne({"UserId":"ProfileA0001",
                          "UserEmail":SignUpUserEmail,
                          "UserPassword":SignUpUserPassword,
                          "UserName":SignUpUserName,
                          "IsEmailAuthenticated":"false"
                        }, function(err, res){
          if (err) throw err;
          SignUpErr = "document inserted"
          console.log("SignUpErr inside:", SignUpErr)
        })
      })
    } else {
      SignUpErr = "Email already has been registered."
      console.log("SignUpErr inside:", SignUpErr)
    }
  })
})

  console.log("SignUpErr outside:", SignUpErr)
  myObj = {"SignUpErr":SignUpErr};
  myJSON = JSON.stringify(myObj);
  res.end(myJSON);
}).listen(9000);

注意:“SignUpErr inside:”给出正确的结果。但是,“SignUpErr outside:”将其显示为未定义。

标签: node.jsmongodb

解决方案


注意:“SignUpErr inside:”给出正确的结果。但是,“SignUpErr outside:”将其显示为未定义。

这是因为 nodejs 的异步特性。SignUpErrundefined一直持续到它在db.collection('Profiles',function(){})调用中被初始化。

因此,要解决此问题,您需要在db.collection('Profiles',function(){}). 也就是说,在初始化之后。

对您的代码进行这些更改,

'use strict';

const http = require('http');

http.createServer(function (req, res) {

  res.statusCode = 200; // Setting the status code
  res.setHeader('Content-Type', 'text/plain');  // Setting the content-type for response

  let {SignUpUserEmail, SignUpUserPassword, SignUpUserName} = url.parse(req.url, true).query;

  MongoClient.connect("mongodb://localhost:27017/ABC", function (err, database) {
    if (err) {
      throw err;
    }

    let db = database.db('ABC');

    db.collection('Profiles').findOne({
      UserEmail: SignUpUserEmail
    }, function (err, result) {
      if (err) {
        throw err
      }

      if (result) {
        let msg = "Email already has been registered.";
        console.log("SignUpErr inside:", msg);

        return res.end(JSON.stringify({
          SignUpErr: "document inserted"
        }));
      }

      db.collection('Profiles', function (err, collection) {
        if (err) throw err;
        collection.insertOne({
          "UserId": "ProfileA0001",
          "UserEmail": SignUpUserEmail,
          "UserPassword": SignUpUserPassword,
          "UserName": SignUpUserName,
          "IsEmailAuthenticated": "false"
        }, function (err, dbresult) {
          if (err) {
            throw err;
          }
          let msg = "document inserted";
          console.log("SignUpErr inside:", msg);

          return res.end(JSON.stringify({
            SignUpErr: "document inserted"
          }));

        })
      });

    });
  });

}).listen(9000);

推荐阅读