如何在express.js应用程序中注册异步中间件模块? [英] How to register async middleware module within express.js app?
问题描述
我正在开发一个Express应用程序,该应用程序使用带有MongoDB后端的 node_acl 模块。我制作了一个模块,该模块创建node_acl的实例并对其进行异步配置。该中间件应被称为堆栈上的第二个中间件,以控制请求访问。
I'm working on an express app that uses the node_acl module with a MongoDB backend. I made a module that creates an instance of node_acl and configures it asynchronously. This middleware should be called as the second middleware on the stack to control request access.
// myModule.js
exports.init = function(callback) {
mongodb.connect("mongodb://localhost:27017/mydb", function(error, db) {
var mongoBackend = new acl.mongodbBackend(db, 'acl_');
acl = new acl(mongoBackend);
// Defining roles for acl
....
acl.addRoleParents('..', '..', function(err){
if (err) callback(err, acl);
acl.addRoleParents('..', '..', function(err){
if (err) callback(err, acl);
acl.addRoleParents('..', ['..','..'], function(err){
if (err) {
callback(err, acl);
} else {
callback(null, acl);
};
});
});
});
});
};
如何将该模块注册为堆栈的第二个中间件?我需要以某种方式编辑myModule.js吗?
How can I register this module to be the second middleware of the stack? Do I need to edit myModule.js in some way?
谢谢你们
推荐答案
该模块已经已提供Express中间件,它很简单:
That module already provides an Express middleware, so it's as simple as:
// ...
var myModule = require('./myModule');
myModule.init(function(err, acl) {
if (err) throw err;
// insert first `app.use()` here
app.use(acl.middleware());
// insert other middleware/route handlers here
});
尽管我应该用您现有的代码注意几件事:
Although I should note a couple of things with your existing code:
-
如果(err)回调(err,acl);
应更改为if(err)返回callback(err);
以防止在调用回调后进一步执行。
if (err) callback(err, acl);
should be changed toif (err) return callback(err);
to prevent further execution after the callback is called.
如果(错误)返回回调(错误);
在 mongodb.connect()
回调内部丢失,以防出现连接错误。
if (error) return callback(error);
is missing right inside the mongodb.connect()
callback in case there is a connection error.
这篇关于如何在express.js应用程序中注册异步中间件模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!