存储在`res.locals`中的Express.js:变量未在视图中定义

时间:2016-11-28 08:17:39

标签: node.js express pug

在快递申请中,我使用app.js中声明的快递路由器作为:

var adminRouter = require('./admin');
app.use("/admin", adminRouter); 

所以它引用我在其中定义此特定路由的admin.js文件:

 router.route('/rooms/edit/:id')
    .all(function(req, res, next) {
        var roomid = req.params.id;
        var room = _.find(rooms, r => r.id == roomid);
        if (!room) {
            res.sendStatus(404);
            return;
        }
        res.locals.room = room;
        next();
    }).get(function(req, res) {

        res.render('edit', { room: room });
    }).post(function(req, res) {

        res.locals.room.name = req.body.name;
        res.redirect('./'); 
    });

但是在编辑房间名称的视图中(由上面路由中的.get方法访问)我收到此错误,指出我room中存储的res.locals变量未定义:

ReferenceError: room is not defined

这是整个app.js

var express = require('express');
var app = express();
var bodyParser =  require('body-parser');


app.set("views", "./views");
app.set("view engine", "jade");

app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended:true}));


app.use(function(req, res, next){
    console.log('incomming req : ' + req.url);
    next();
});

app.get('/', function(req, res){
    res.render('index', {title:'Home'});
});

var adminRouter = require('./admin');
app.use("/admin", adminRouter);

app.listen(3000, function(){
    console.log('app running on port 3000');
});

这也是edit.jade视图:

extends layout
block content
 h1 Edit chatroom!!
 form(method="POST")
      fieldset.form-group
          label(for="name") Name:
          input.form-control(name="name", type="text", placeholder="Enter a name" value="#{room.name}")
          small.text-muted Give your chatroom a meaningful name for people to refer to it.
      button.btn.btn-primary(type="submit") Save chatroom
      a.btn.btn-default(href="/admin/rooms") Cancel     

1 个答案:

答案 0 :(得分:1)

  

我收到此错误,指出我room中存储的res.locals变量未定义:

ReferenceError: room is not defined

这不是错误所说的内容:它表示未定义名为room变量。它本应该指向发生错误的代码行,在这里:

res.render('edit', { room: room });

事实上,room 未定义。