【发布时间】:2013-09-04 02:59:03
【问题描述】:
我刚刚解压了 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 = { ...
在同一个配置文件夹中,我创建了名为 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') );
只有当我执行上述操作时,它才告诉我它找不到 express 模块。我已经验证 express 是 Sails 的 node_modules 中的一个模块。是否有另一种语法来加载它?我宁愿不必在风帆旁边安装第二个 express 副本。有没有办法访问原始 Sails/Express 应用程序实例?
【问题讨论】: