我剛剛解開了Node框架Sails.js的全新副本。它是建立在快速3.在/config/routes.js文件是這樣的評論:如何在Sails.js中使用自定義路由中間件? (ExpressJS)
/**
* (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文件相同的config文件夾。
// 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是Sails的node_modules中的一個模塊。是否有另一種加載語法?我寧願不必安裝帆船的第二個快遞副本。有沒有辦法訪問原始的Sails/Express應用程序實例?
THX添加customMiddleware。(+1),但我不認爲我會這樣寫 - thx爲我們箭袋中的額外箭頭。 – Cody