3

エクスプレス初心者です。私がルーティングを行っている方法は、エラーをキックバックすることです。

これが私の関連コードです:

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);

コード構造がインデックス ページへのルーティングと同じであり、インデックス ページが完全に読み込まれるため、これが機能しない理由がわかりません。

何か案は?ありがとう

4

1 に答える 1

6

問題は、おそらくaが期待されるroutes.playときです。undefinedfunction

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');
};

ディレクトリを要求すると、通常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);
    
于 2013-08-19T23:46:55.513 に答える