node.js - 执行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:”将其显示为未定义。
解决方案
注意:“SignUpErr inside:”给出正确的结果。但是,“SignUpErr outside:”将其显示为未定义。
这是因为 nodejs 的异步特性。SignUpErr
将undefined
一直持续到它在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);
推荐阅读
- python - 当我使用快捷运算符转换表达式时,输出错误
- c# - RaycastHit2D 未检测到对游戏对象的触摸
- python - 如何在openCV python中输出一系列图像
- python - 迭代表名并更新查询
- javascript - 元素输入类型=文本无法输入越南语
- android - 如何将 Single observable 运算符与 Location 对象一起使用
- android - 关于 Android 的 build.gradle 中的 Google Play 服务库的错误
- sql-server - SQL - 如果不存在则插入表中 - 使用现有的 NULL 值
- c# - TSQL 多个连接与来自 ASP.NET Core 的多个请求?
- pandas - 使用 iloc 从另一个查找数据帧