【问题标题】:Express.js basic routing from index.js file来自 index.js 文件的 Express.js 基本路由
【发布时间】:2013-01-29 12:46:42
【问题描述】:

我想创建 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

【问题讨论】:

  • 您的主要app.js 文件看起来如何?你有app.get('/room', routes.room) 路线或类似的东西吗?
  • @zeMirco 是的,我现在做到了,它解决了问题。你可以写作为答案。我必须为每一页做吗?如果我有很多页面怎么办,有没有办法获取 index.js 路由文件中的所有页面?

标签: routes express


【解决方案1】:

您必须将路由添加到您的主 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);
  }
});

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

因此,最好的办法是将您与/room 相关的POSTGET 请求放入room.js 中,并在您的主要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 存储库中的 route-separation 示例。

【讨论】:

    猜你喜欢
    • 2014-10-09
    • 2017-01-24
    • 1970-01-01
    • 2019-07-18
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 1970-01-01
    相关资源
    最近更新 更多