繁体   English   中英

Nodejs无法响应多个mongoose连接测试请求

[英]Nodejs not able to respond to more than one request for mongoose connection test

我对mongoose和node很新。 我正在尝试使用Nodejs和Express编写一个简单的API,其中我发送一个MongoDB URI,如果它有效,即用户名/密码组合工作并且成功建立了与该URI的连接,则应返回成功消息。

我最初尝试创建一个单独的函数来尝试连接到给定的URI:

function testURI(uri) {
   mongoose.connect(uri, {useNewUrlParser: true} );
   mongoose.connection.on("connected", function() { return true } );
}

module.exports.test = function(req, res) {
   var uri = req.body.uri;
   if(testURI(uri)) res.status(200).json({'success': true});
   else res.status(400).json({'success': false});
};

但这失败了,因为mongoose异步连接,并且“连接”事件回调无法为主函数返回true

所以我放弃了单独功能的想法,而是尝试在module.exports.test函数中实现它:

module.exports.test = function(req, res) {
   var uri = req.body.uri;
   mongoose.connect(uri, { useNewUrlParser: true, connectTimeoutMS: 2500 });

   mongoose.connection.on("connected", function() {
       mongoose.connection.close();
       res.status(200).json({'success': true});
   });

 mongoose.connection.on("error", function(err) {
        result = {
            'error': true,
            'errorMsg': 'Error: Could not connect to the given host.'
        }
        mongoose.connection.close();
        res.status(400).json(result);
    });
};

这很好,除了服务器在响应一个请求后死亡。 一旦我尝试使用无效的URI,它会按预期返回HTTP 400,但是当我发送另一个具有不同URI的请求时,应用程序只会因错误而崩溃

错误:发送后无法设置标头。

然后我必须重新启动应用程序才能发送另一个请求。 显然,同一控制器中的两个独立的res.status(200).json res.status(400).jsonres.status(400).json正在创建问题,并且应用程序也将后续请求也视为同一请求。

通过创建自定义中间件来解决问题。 而不是通过控制器函数中的res.status().json()返回结果,我使用此函数作为中间件并从下一个函数返回结果

module.exports.test = function(req, res, next) {
   var uri = req.body.uri;
   mongoose.connect(uri, { useNewUrlParser: true, connectTimeoutMS: 2500 });

   mongoose.connection.on("connected", function() {
       mongoose.connection.close();
       req.status = 200;
       req.result = {'success': true};
       next();
   });

 mongoose.connection.on("error", function(err) {
        result = {
            'error': true,
            'errorMsg': 'Error: Could not connect to the given host.'
        }
        mongoose.connection.close();
        req.status = 400;
        req.result = result;
        next();
    });
};

module.exports.returnDb = function(req, res) {
    res.status(req.status).json(req.result);
};

编辑路线声明:

router.route('/test')
.post(client.test, client.returnDb);

暂无
暂无

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

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