.routes
routes
功能允許自訂 Hook 在載入時輕鬆地將新路由綁定到 Sails 應用程式。如果實作了 routes
,它應該是一個物件,包含 before
鍵、after
鍵或兩者兼具。這些鍵的值應該反過來是物件,其鍵是 路由位址,而其值是帶有標準 (req, res, next)
參數的路由處理函式。在 before
物件中指定的任何路由都將在自訂使用者路由(如 sails.config.routes 中定義)和 藍圖路由之前 綁定。相反地,在 after
物件中指定的路由將在自訂路由和藍圖路由之後 綁定。例如,考慮以下 count-requests
Hook
module.exports = function (sails) {
// Declare a var that will act as a reference to this hook.
var hook;
return {
initialize: function(cb) {
// Assign this hook object to the `hook` var.
// This allows us to add/modify values that users of the hook can retrieve.
hook = this;
// Initialize a couple of values on the hook.
hook.numRequestsSeen = 0;
hook.numUnhandledRequestsSeen = 0;
// Signal that initialization of this hook is complete
// by calling the callback.
return cb();
},
routes: {
before: {
'GET /*': function (req, res, next) {
hook.numRequestsSeen++;
return next();
}
},
after: {
'GET /*': function (req, res, next) {
hook.numUnhandledRequestsSeen++;
return next();
}
}
}
};
};
這個 Hook 將透過 before
物件中提供的函式處理所有請求,並遞增其 numRequestsSeen
變數。它也將透過 after
物件中提供的函式處理任何未處理的請求——也就是說,任何未透過自訂路由配置或藍圖在應用程式中綁定的路由。
在 Hook 中設定的這兩個變數將可供 Sails 應用程式中的其他模組使用,名稱為
sails.hooks["count-requests"].numRequestsSeen
和sails.hooks["count-requests"].numUnhandledRequestsSeen