如何使用Sails.js自定义路由中间件? (ExpressJS)
我刚解开了一个Node框架Sails.js的新副本。 它构build在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 = { ...
在同一个configuration文件夹中,我创build了名为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 // ... } };
我的目的是使非Ajax GET请求都加载相同的模板文件,所以我的CanJS应用程序可以设置基于URL的应用程序状态(所以我的JavaScript应用程序是正确的书签)。
我想运行该脚本作为中间件。 有人可以告诉我如何使用app.use()在这种情况下使is_ajax.js脚本之前运行其他路由?
我猜这是类似的
var express = require('express'); var app = express(); app.use( require('./is_ajax') );
只有当我这样做,它告诉我,它无法find快速模块。 我已经validation了express是Sails的node_modules中的一个模块。 是否有另一种加载语法? 我宁愿不必在帆上安装第二份快件。 有没有办法访问原来的Sails / Express应用程序实例?
您可以使用策略来实现这一点。 将isAjax
函数保存为isAjax.js,并将其更改为仅使用module.exports
而不是module.exports.isAjax
。 然后在config / policies.js文件中,可以指定应用策略的控制器/操作 – 为每条路由运行isAjax
,只需执行以下操作:
'*':'isAjax'
在那个文件里
我有同样的问题搞清楚如何使用中间件。 它们基本上在config/policies.js
定义。
所以,如果你想使用旧式的中间件 (又名策略 ),你可以这样做(这可能不是最好的方法):
// config/policies.js '*': [ express.logger(), function(req, res, next) { // do whatever you want to // and then call next() next(); } ]
但是,真正的方法是将所有这些策略放在api/policies/
文件夹中
为了添加express的中间件,我find了这个线程和
sails-middleware-example-issue是非常有用的。
- 安装快递本地:
npm install express
- load express:
var exp = require('express')
- 在
$app_dir/config/local.js
app_dir$app_dir/config/local.js
添加$app_dir/config/local.js
express: { customMiddleware: function (app) { console.log("config of Middleware is called"); app.use(exp.logger()); app.use(exp.compress()); app.use(function (req, res, next) { console.log("installed customMiddleware is used"); next(); }) } }