0

我想创建 2 个页面,使用 2 个玉文件。以下方式有什么问题:

exports.index = function(req, res){
    res.render('index', { title: 'Welcome' });
};

exports.room = function(req, res){
    res.render('room', { title: 'Game' });
};

该指数localhost:3000有效。但localhost:3000/room给了我

Cannot GET /room
4

1 回答 1

0

您必须将路线添加到主app.js文件

app.get('/room', routes.room);

对于很多页面,您可以执行类似的操作

var routes = ['blog', 'about', 'home', 'team', 'room', ...];

routes.forEach(function(item) {
  exports[item] = function(req, res) {
    res.render(item);
  }
});

但是,如果您有很多单独的局部变量,这也可能会变得混乱(您可以在数组中使用对象而不是字符串)。

所以最好的办法是将你的POSTGET请求/room放在 a 中room.js,并在你的 main 中要求它app.js。然后你可以像这样使用它

var room = require('./routes/room');

app.get('/room', room.read);
app.post('/room', room.create);
app.get('/room/:id', room.getID);
app.get('/room/anything', room.anything);

// then continue with app.get('/team') for example

还可以查看 express github repo 中的route-separation示例。

于 2013-01-29T16:08:40.983 回答