エクスプレスでは、他のすべてが一定に保たれていますが、次の間に違いがあります。
app.all('/', mongoProxy(config.mongo.dbUrl, config.mongo.apiKey));
そして
app.all('/', function (req, res) {
mongoProxy(config.mongo.dbUrl, config.mongo.apiKey);
});
前者はからの戻り値を返すことができますがmongoProxy
、後者はそうではありません。mongoProxy
次のようになります。
module.exports = function(basePath, apiKey) {
basePath = url.parse(basePath);
// Map the request url to the mongolab url
// @Returns a parsed Url object
var mapUrl = module.exports.mapUrl = function(reqUrlString) {
//use the basePath to Parse the URL
return newUrl;
};
var mapRequest = module.exports.mapRequest = function(req) {
var newReq = mapUrl(req.url);
// Make a new request and return it..
return newReq;
};
var proxy = function(req, res, next) {
try {
var options = mapRequest(req);
// Create the request to the db
var dbReq = https.request(options, function(dbRes) {
// Save result
});
// { send result }
res.send(data);
res.end();
});
});
// send request
dbReq.end(JSON.stringify(req.body));
} catch (error) {
//..
}
};
return proxy;
};
ドキュメントは、2つの概念の違いを説明する上で明確ではありません。私が見た例では、前者の機能
app.all('/', mongoProxy(config.mongo.dbUrl, config.mongo.apiKey));
後者のように実際に渡されることなく、reqおよびresオブジェクトにアクセスできますfunction (req, res)
。
2つの違いは何ですか?1つが望ましいですか?
はい、違いがあります。最初の関数は機能しますが、2番目の関数はハングします(によって返される匿名関数を呼び出さないでくださいmongoProxy
)。表現するのがより慣用的であるため、最初の方が望ましいです(ミドルウェアを使用しています)。
まず、ノート方法ではmongoProxy
、あなたreturn proxy
、無名関数:
module.exports = function(basePath, apiKey) {
/* snip */
var proxy = function(req, res, next) { // <-- here
/* snip */
};
return proxy; // <-- and here
};
それを分解しましょう:
var proxy = mongoProxy(config.mongo.dbUrl, config.mongo.apiKey)
// proxy is an anonymous function which accepts: (req, res, next)
app.all('/', proxy);
// express will use proxy as the callback (middleware), which means this is the same as:
app.all('/', function (req, res, next) {
proxy(req, res, next)
})
2番目の例を書き直してみましょう。これにより、機能しない理由が明確になります。
var proxy = mongoProxy(config.mongo.dbUrl, config.mongo.apiKey)
app.all('/', function (req, res) {
proxy // nothing happens because you don't invoke the function
});
あなたは第二の例を使用する場合は、呼び出すことができproxy
てproxy(req, res, next)
、これは(一般的には、特に明示のために)慣用的ではありません。Expressはすべてミドルウェアに関するものなので、最初の例を使用してください。
これは、クロージャを使用する別の例です(mongoProxy
関数とよく似ています)。
function getPermissionLevelMiddleware (level) {
// returns an anonymous function which verifies users based on `level`
return function (req, res, next) {
if (req.isAuthenticated() && req.user.permission.level > level)
return next()
return res.redirect('/no/permission')
}
}
var isAdmin = getPermissionLevelMiddleware(9000)
// `isAdmin` only allows users with more than 9000 `user.permission.level`
var isPleb = getPermissionLevelMiddleware(1)
// `isPleb` allows users with more than 1 `user.permission.level`
app.get('/admin', isAdmin, function (req, res) {
res.render('admin.jade')
})
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加