2013-01-12 43 views
0

如何確保特定對象可用於我處理的每個請求?將默認值分配給快遞公司的請求對象

var somethingImportant = "really important"; 
var app = express(); 

// This is just a hypothetical example of what I'm after... 
app.mixThisInWithRequest({ 
    somethingImportant: somethingImportant 
}); 

app.use(function (request, response, next) { 
    console.log(request.somethingImportant); 
}); 

鑑於上面的例子,是否有類似於mixThisInWithRequest函數的設施?

回答

2

將其添加到中間件request對象,在app.use鏈,早在你需要它:

var somethingImportant = "really important"; 
var app = express(); 

app.use(function (request, response, next) { 
    request.somethingImportant = somethingImportant; 
    next(); 
}); 
app.use(function (request, response, next) { 
    console.log(request.somethingImportant); 
}); 
+0

這發生在我身上,我只是想確保野蠻與閉合迫使它不會傷害的東西... –

+1

沒有真正的蠻力。這是快速/連接的方式。 – JohnnyHK