我一直在研究一個非常基本的nodejs問題,因爲這個時間太長了,我被卡住了。其他人也提過類似的問題,但由於某些原因,答案似乎對我無效。從Backbone.Router模板訪問res.locals
背景:
我只是在斜坡上升與快遞,骨幹,&護照進行身份驗證的NodeJS。 Passport將用戶對象存儲在請求中,所以我試圖將它傳遞給我的Backbone視圖。
我一直在使用Node Cellar項目作爲起點,並通過Backbone.Router.extend跟隨他們的主角顯示我的大部分視圖。
我想要做的事:
我只是想給用戶對象傳遞到一個視圖和顯示器,例如我的模板中有一個名字。
我已經試過:
我使用類似於下面的中間件到我的用戶通過該模型
app.use(function(req, res, next){
res.locals.user = req.user;
next();
});
當我app.get直接我能證實使用這個作品:
app.get('/test',function index(req, res) {
res.send(res.locals.user);
});
不過,如果我包括我的HeaderView.html以下文件都壞了(即使我可以確認用戶通過app.get定義):
<%= user === null ? "No user" : user %> (or user.name.familyName, etc.)
我得到以下錯誤在控制檯:
Uncaught ReferenceError: user is not defined
這裏是我main.js是什麼樣子:
var AppRouter = Backbone.Router.extend({
routes: {
"home" : "home"
},
initialize: function() {
this.headerView = new HeaderView();
$('.header').html(this.headerView.el);
var footerView = new FooterView();
$('#footer').html(footerView.el);
},
home: function (id) {
if (!this.homeView) {
this.homeView = new HomeView();
}
$('#content').html(this.homeView.el);
},
});
utils.loadTemplate(['HomeView'], function() {
app = new AppRouter();
Backbone.history.start();
});
下面是我設置了快遞:
app.set('port', process.env.PORT || 3000);
app.use(express.logger('default')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser()),
app.use(express.static(path.join(config.root, 'public')));
app.use(express.cookieParser('optional secret string'));
app.use(express.session({ secret: 'my secret secret key' }));
app.use(passport.initialize());
app.use(passport.session());
有什麼想法?
這聽起來像路徑渲染模板在設置'res.locals'的中間件之前聲明。顯示爲模板提供服務的路由,以及Express的路由設置。 – robertklep
嗯,掛在......我想你可能會混淆客戶端模板和服務器端模板。 'res.locals'變量是服務器端模板的一部分,這意味着它不會在任何客戶端模板中自動顯示爲變量。您需要首先通過服務器端模板引擎來處理這些內容。 – robertklep
我認爲這可能會導致問題...當我使用app.get時,如下所示:'app.get('/',function(reg,res){console.log(「test」);}); '看來我的服務器端路由沒有被擊中。不知道爲什麼,但我的猜測是服務器靜態地服務於路由,然後依靠Backbone進行導航。 – silvermanip