简体   繁体   English

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

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

I'm fairly new to mongoose and node. 我对mongoose和node很新。 I am trying to write a simple API using Nodejs and Express, wherein I send a MongoDB URI, and if it is valid, ie the username/password combo works and a connection to that URI is successfully established, a success message should be returned. 我正在尝试使用Nodejs和Express编写一个简单的API,其中我发送一个MongoDB URI,如果它有效,即用户名/密码组合工作并且成功建立了与该URI的连接,则应返回成功消息。

I initially tried to create a separate function to try to connect to the given 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});
};

But this failed, since mongoose connects asyncronously, and the "connected" event callback is not able to return true for the main function 但这失败了,因为mongoose异步连接,并且“连接”事件回调无法为主函数返回true

So I dropped the idea for a separate function, and instead tried to achieve it within the module.exports.test function: 所以我放弃了单独功能的想法,而是尝试在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);
    });
};

This works fine, except that the server dies after responding to one request. 这很好,除了服务器在响应一个请求后死亡。 Once I try with an invalid URI, it returns HTTP 400 as expected, but then when I send another request with a different URI, the app just crashes with the error 一旦我尝试使用无效的URI,它会按预期返回HTTP 400,但是当我发送另一个具有不同URI的请求时,应用程序只会因错误而崩溃

Error: Can't set headers after they are sent. 错误:发送后无法设置标头。

And then I have to restart the app before I can send another request. 然后我必须重新启动应用程序才能发送另一个请求。 Apparently the two separate res.status(200).json and res.status(400).json in the same controller are creating the problem and the app is treating subsequent requests also as the same request. 显然,同一控制器中的两个独立的res.status(200).json res.status(400).jsonres.status(400).json正在创建问题,并且应用程序也将后续请求也视为同一请求。

Fixed the problem by creating a custom middleware. 通过创建自定义中间件来解决问题。 Instead of returning the result via res.status().json() within the controller function, I used this function as a middleware and returned the result from the next function 而不是通过控制器函数中的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);
};

Edited route declaration: 编辑路线声明:

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

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

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