0
在明示應用,我使用在app.js
作爲聲明明示路由器:Express.js:變量存儲在`res.locals`未在該視圖中定義
var adminRouter = require('./admin');
app.use("/admin", adminRouter);
所以它引用其中i的所限定的本特定路由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('./');
});
但在用於編輯房間名稱(通過在上面的路由。獲得方法訪問)的視圖我得到這個錯誤說,room
變量i存儲在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