【问题标题】:Node.js / Express routingNode.js / 快速路由
【发布时间】:2013-08-20 08:02:41
【问题描述】:

我是 Express 的新手。我做路由的方式是在回退一个错误。

这是我的相关代码:

app.js

var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path')
  , firebase = require('firebase');

...

// Routing
app.get('/', routes.index);
app.get('/play', routes.play);

index.js 和 play.js

exports.index = function(req, res){
  res.sendfile('views/index.html');
};

exports.play = function(req, res){
  res.sendfile('views/play.html');
};

这是错误:

错误:.get() 需要回调函数,但得到了 [object Undefined]

它在 app.js 中引用了这一行

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

我不知道为什么这不起作用,因为用于路由到我的索引页面的代码结构相同,并且索引页面加载完美。

有什么想法吗? 谢谢

【问题讨论】:

  • routes.js 在您的当前目录中吗?在初始化快速检查 routes 是否为 undefined 之前,请快速输入一行。可能只是一个路径问题。
  • @Joe 是的,据我所知,路径是正确的。它加载 index.js(然后是 index.html)就好了。 play.js 和 play.html 的位置与 index 相同

标签: node.js routing express


【解决方案1】:

问题可能是routes.playundefined,而应该是function

console.log(typeof routes.play); // ...

如果您的routes 至少作为注释“index.js 和 play.js”被拆分为多个文件,则建议:

// routes/index.js
exports.index = function(req, res){
  res.sendfile('views/index.html');
};
// routes/play.js
exports.play = function(req, res){
  res.sendfile('views/play.html');
};

需要一个目录通常只会include the index.js。所以,你仍然需要在某个地方require('./play')自己。

  1. 您可以在index.js 内“转发”它:

    exports.index = function(req, res){
      res.sendfile('views/index.html');
    };
    
    var playRoutes = require('./play');
    exports.play = playRoutes.play;
    

    或者:

    exports.play = require('./play');
    
    app.get('/play', routes.play.play);
    
  2. 或者也可以直接在app.js 中要求:

     var express = require('express')
      , routesIndex = require('./routes')
      , routesPlay = require('./routes/play')
    // ...
    
    // Routing
    app.get('/', routesIndex.index);
    app.get('/play', routesPlay.play);
    

【讨论】:

  • 谢谢,就是这样。当我console.log(typeof routes.play) 它给了我未定义的。所以我按照选项 2 将其拆分。谢谢,你帮我清理了
猜你喜欢
  • 2015-10-27
  • 1970-01-01
  • 2019-08-28
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 2018-10-06
  • 1970-01-01
  • 2017-02-26
相关资源
最近更新 更多