节点应用程序路由无效

时间:2015-06-01 08:38:15

标签: javascript node.js express

我对节点JS很新,我创建了以下3个文件,在保存应用程序时出错了

http.createServer(app).listen(**app.get('port')**, function(){

错误未定义不是函数 我使用nodemon,我在终端中看到错误

我想保留文件的结构(从不同的文件启动服务器 - server.js),因为我想使用TDD。

这是文件

server.js

var http = require('http');

app = require('./app');
http.createServer(app).listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));
});

app.js

module.exports = function() {
    var express = require('express'),
        app = express();

    app.set('port', process.env.PORT || 3000);
    app.use(require('./controllers/requests'));
    return app;

}

requests.js

var routers = require('express')
    , router = express.Router()

router.get('/wild', function(req, res) {
    debugger;
    res.send('Wolf, Fox, Eagle')
})

module.exports = router

更新 这是代码中的更新 app.js

  module.exports = function() {
        var express = require('express'),
            app = express();

        app.set('port', process.env.PORT || 3000);
        app.use(function(){
            var routes = require('./controllers/requests') (app);
        });
        return app;

    }

requests.js **

module.exports = function (app) {
    var express = require('express')
        , router = express.Router();
    app.get('/wild', function(req, res) {
        res.send('Wolf, Fox, Eagle');
    })
}

server.js

var http = require('http');

app = require('./app');
http.createServer(app).listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));
});**

1 个答案:

答案 0 :(得分:2)

您应该调用包含app的模块返回的函数。

app = require('./app') ();

此外,在 request.js 文件中,您应该在应用实例上定义路线:

module.exports = function (app) {
   app.get('/wild', function(req, res) {
      res.send('Wolf, Fox, Eagle');
   })
}

app.js 中: app.use(function(){})用于定义中间件。在这里你可以打电话

var routes = require('./controllers/requests') (app);

修改

请在下面的回顾中回答您的意见:

<强> server.js

var http = require('http');
var app = require('./app') ();
http.createServer(app).listen(app.get('port'), function(err){
   console.log('Express server listening on port ' + app.get('port'));
});

<强> app.js

module.exports = function() {
   var express = require('express'),
      app = express();

    app.set('port', process.env.PORT || 3000);
    require('./controllers/requests')(app);
    return app;
}

<强> requests.js

module.exports = function (app) {
   app.get('/wild', function(req, res) {
      res.send('Wolf, Fox, Eagle')
 });
}

希望这有帮助!