《NodeJs 开发指南》从express2.0到3.0遇到的问题,求help!
发布于 2年前 作者 fedaniel 1588 次浏览

app.js:

   app.locals({
        inspect: function (obj) {
            return util.inspect(obj, true);
        }
    });
    
    app.use(function (req, res, next) {
        res.locals.headers = req.session.headers;
        next();
    });
    
    app.get('/helper', function (req, res) {
        res.render('helper', {
            title: 'Helpers',
            layout: 'helper'
        });
    });

helper.ejs:

<%=inspect(headers)%>

报错:

ReferenceError: /home/dd/workspace/microblog/views/helper.ejs:1
 >> 1| <%=inspect(headers)%>
    2| 

headers is not defined
    at eval (eval at <anonymous> (/home/dd/workspace/microblog/node_modules/ejs/lib/ejs.js:234:12))
    at exports.compile (/home/dd/workspace/microblog/node_modules/ejs/lib/ejs.js:239:15)
    at Object.exports.render (/home/dd/workspace/microblog/node_modules/ejs/lib/ejs.js:277:13)
    at View.exports.renderFile [as engine] (/home/dd/workspace/microblog/node_modules/ejs/lib/ejs.js:303:22)
    at View.render (/home/dd/workspace/microblog/node_modules/express/lib/view.js:75:8)
    at Function.app.render (/home/dd/workspace/microblog/node_modules/express/lib/application.js:502:10)
    at ServerResponse.res.render [as partial] (/home/dd/workspace/microblog/node_modules/express/lib/response.js:716:7)
    at ServerResponse.module.exports.res.render (/home/dd/workspace/microblog/node_modules/express-partials/index.js:55:9)
3 回复

headers is not defined , 你指派的模版变量只有title和layout ,并没有指定headers这个变量。

加了headers:res.locals.headers 页面显示undefined express2.0到3.0 app.dynamicHelpers()改成use middleware + res.locals这个方式,我怀疑我用的不对,locals全局的值始终获取不到

res.locals 是有生命周期的,所以必须指派到模板变量里…… 或者 function localsVariable(req, res, next) { res.locals.key = value; } app.get(url, localsVariable, callback);

回到顶部