Node.js / Express 路由

3

我是一名新手,刚开始学习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 文件?在初始化 express 之前,加入一行代码来检查 routes 是否为 undefined。这可能只是一个路径问题。 - Joe
@Joe,就我所知,路径设置是正确的。它成功地加载了index.js(然后加载index.html)。play.js和play.html的位置与index相同。 - JDillon522
1个回答

6
问题可能是当期望一个函数时,routes.playundefined
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');
};

通常只需使用 require 函数加载目录,会自动包含该目录下的 index.js 文件。所以你仍然需要在某个地方手动调用 require('./play')

  1. You can either "forward" it within index.js:

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

    Alternatively:

    exports.play = require('./play');
    
    app.get('/play', routes.play.play);
    
  2. Or require it directly in app.js as well:

     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) 时,它返回了 undefined。所以我按照选项2进行了拆分。感谢你,你帮我澄清了这个问题。 - JDillon522

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接