我是 P'unk Avenue 的 Apostrope 的首席建筑师。
你不想延长apostrophe-express
模块以新名称命名。该模块提供了apos.app
单例,因此将其扩展为新名称即可apos.app
两次,导致混乱和潜在的问题。
拦截每个 Express 请求
相反,只需利用middleware
的选项apostrophe-express
模块。你可以这样做app.js
:
var apos = require('apostrophe')({
modules: {
// Other module configuration here, then ...
'apostrophe-express': {
middleware: [
function(req, res, next) {
// Do whatever you like here
console.log(req.url);
// Let the request continue. You could also
// use res.redirect, res.send, etc. and
// bypass Apostrophe, in which case you
// should NOT call next
return next();
}
]
}
}
});
这就是您所需要的,您可以使用require
从另一个文件中提取中间件功能,减少混乱app.js
。然而值得指出的是,您可以将此代码移至lib/modules/apostrophe-express/index.js
文件中的项目,以“隐式子类化”该模块。这打开了提供您自己的大门construct
属性也是如此,如果您愿意的话,这将允许您覆盖模块的任何方法。
如果您以这种方式处理它,则无需触摸app.js
at all:
// in lib/modules/apostrophe-express/index.js at project level
module.exports = {
middleware: [
function(req, res, next) {
console.log(req.url);
return next();
}
],
construct: function(self, options) {
// If you want, override methods of the module here
};
};
在页面渲染之前拦截请求
您指定了“每个页面请求”,我将其解释为“每个网络请求”。但您可能只需要 Apostrope 将要构建并发送正确网页的请求。
为此,只需添加一个pageBeforeSend
方法到您自己的任何模块。假设我们的模块名为cool-stuff
:
// in app.js
var apos = require('apostrophe')({
modules: {
// Other module configuration here, then ...
'cool-stuff': {}
}
});
// In lib/modules/cool-stuff/index.js
module.exports = {
construct: function(self, options) {
self.pageBeforeSend = function(req, callback) {
// Careful, there isn't always a page object; we could be
// rendering /login for instance
console.log(req.data.page && req.data.page._url);
return callback(null);
};
}
};
撇号总是调用pageBeforeSend
对于每个具有此类方法的模块。
如上所述,注意不要假设req.data.page
已设置,因为在某些情况下,Apostrope 会渲染完整的网页作为响应,但 Apostrope 的页面树中没有相应的页面对象。
页面对象加载后立即拦截
还有一种选择:如果pageBeforeSend
这个过程对你来说太晚了,例如因为你希望小部件加载器看到你所做的更改req
, use pageServe
反而...
// in app.js
var apos = require('apostrophe')({
modules: {
// Other module configuration here, then ...
'cool-stuff': {}
}
});
// lib/modules/cool-stuff/index.js
module.exports = {
construct: function(self, options) {
self.pageServe = function(req, callback) {
// Express request URL
console.log(req.url);
// URL of the best matching page available
console.log((req.data.page || req.data.bestPage)._url);
return callback(null);
};
}
};
请注意,我允许req.data.page
or req.data.bestPage
存在。如果 URL 与页面不完全匹配,撇号将设置req.data.bestPage
到与 URL 匹配的最长“路径前缀”的页面。例如,如果 URL 是 /foo/bar 并且 /foo 存在,但 /foo/bar 不存在,req.data.bestPage
将/foo
。请注意,这意味着req.data.bestPage
在最坏的情况下将成为主页。
See the apostrophe-custom-pages
模块,您可以用它来做一些巧妙的事情。
希望这有帮助!