Mar*_*son 9 node.js express sails.js
我刚刚解压缩了Node框架Sails.js的新副本.它建立在Express 3上.在/config/routes.js文件中是这个评论:
/**
* (1) Core middleware
*
* Middleware included with `app.use` is run first, before the router
*/
/**
* (2) Static routes
*
* This object routes static URLs to handler functions--
* In most cases, these functions are actions inside of your controllers.
* For convenience, you can also connect routes directly to views or external URLs.
*
*/
module.exports.routes = { ...
Run Code Online (Sandbox Code Playgroud)
在同一个配置文件夹中,我创建了名为is_ajax.js的文件.
// Only run through API on ajax calls.
module.exports.isAjax = function(req, res, next){
if (req.headers['x-requested-with']) {
// Allow sails to process routing
return next();
} else {
// Load main template file
// ...
}
};
Run Code Online (Sandbox Code Playgroud)
我的目的是使非Ajax GET请求都加载相同的模板文件,这样我的CanJS应用程序就可以根据URL设置应用程序状态(所以我的javascript应用程序可以正常书签).
我想将该脚本作为中间件运行. 有人可以告诉我如何在这种情况下使用app.use()让is_ajax.js脚本在其他路由之前运行吗?
我猜它是这样的
var express = require('express');
var app = express();
app.use( require('./is_ajax') );
Run Code Online (Sandbox Code Playgroud)
只有当我执行上述操作时,它才会告诉我它无法找到快速模块.我已经验证了express是Sails'node_modules中的一个模块.是否有其他语法加载它?我宁愿不必在帆旁边安装第二份快递副本.有没有办法访问原始的Sails/Express应用程序实例?
sgr*_*454 19
您可以使用策略来实现此目的.将您的isAjax函数保存为api/policies文件夹下的isAjax.js,并将其更改为仅使用module.exports而不是module.exports.isAjax.然后在config/policies.js文件中,您可以指定要应用策略的控制器/操作 - isAjax为每个路由运行,只需执行以下操作:
'*':'isAjax'
Run Code Online (Sandbox Code Playgroud)
在那个文件中.
ris*_*hjn 10
我有同样的问题,想弄清楚如何使用中间件.它们基本上定义于config/policies.js.
因此,如果您想使用旧样式的中间件(也称为策略),您可以执行以下操作(这可能不是最好的方式):
// config/policies.js
'*': [
express.logger(),
function(req, res, next) {
// do whatever you want to
// and then call next()
next();
}
]
Run Code Online (Sandbox Code Playgroud)
然而,真正的sailjs方式是将所有这些策略放在api/policies/文件夹中
| 归档时间: |
|
| 查看次数: |
12605 次 |
| 最近记录: |