2013-08-31 40 views
8

我剛剛解開了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應用程序實例?

回答

17

您可以使用policies來實現此目的。將您的isAjax函數保存爲您的api/policies文件夾下的isAjax.js,並將其更改爲僅使用module.exports而不是module.exports.isAjax。然後在你的config/policies.js文件,你可以指定哪些控制器/操作的策略應用到 - 運行isAjax爲每路線,只是做:

'*':'isAjax' 
在該文件中

9

我有同樣的問題想辦法如何使用中間件。 它們基本上在config/policies.js中定義。
所以,如果你想使用中間件(又名政策)像老風格,你可以做以下(這可能不是最好的方式):

// config/policies.js 
'*': [ 
    express.logger(), 
    function(req, res, next) { 
    // do whatever you want to 
    // and then call next() 
    next(); 
    } 
] 

然而,真正的sailjs的辦法就是把所有這些政策在api/policies/文件夾

+0

THX添加customMiddleware。(+1),但我不認爲我會這樣寫 - thx爲我們箭袋中的額外箭頭。 – Cody

4

要添加快遞壓縮中間件,我發現這個線程和

sails-middleware-example-issue非常有用。

  1. 安裝表達地方:npm install express
  2. 負荷快遞:var exp = require('express')
  3. $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(); 
     }) 
    } 
    } 
+1

只需要注意 - 您不需要將Express作爲依賴添加,只需在Sails中執行自定義中間件即可!在您的示例中,您正在使用自定義函數中的其他Express中間件,這很好,但如果您沒有這樣做,則可以跳過第1步和第2步。 – sgress454

+0

「express:」已棄用(在sails 0.12.1中) 。使用「http:」 – eyn