Node.js控制器

时间:2014-05-07 19:35:50

标签: javascript node.js express

我目前对Node.js很新 - Express框架,我试图模仿MVC模式,到目前为止我得到了这个

app.js

var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var http = require('http');

var app = module.exports = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.set('port', process.env.PORT || 3000);

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

require('./routes');

/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

http.createServer(app).listen(app.get('port'), function() {
    console.log("Running server");
});

使用快速生成器生成的普通app.js进行了一些修改,现在我的路由/ index.js

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

app.get('/test', function(req, res) {
    require('./controllers/test.js');
    test();
}); 

app.get('/', function(req, res) {
    res.send('yankevf');
}); 

正如您在路由/测试中看到的那样,如果查找模块/controllers/test.js,但由于没有实际的模块,它不会工作..

如何在文件夹控制器中包含文件?因为我的服务器一直在node_modules内搜索

1 个答案:

答案 0 :(得分:3)

看起来你基本上就在那里......

根据您的问题,您的文件夹结构听起来像是:

./app.js
./routes
  -> index.js
./controllers
  -> test.js

如果是这种情况,这应该有效:

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

app.get('/test', function(req, res, next) {
    test = require('../controllers/test.js'); // Note the path, one directory up
    // Passing the req, res, next arguments on to your controller allows it to respond
    // i.e. res.json({msg: 'hello world'}).
    test(req, res, next);
});

虽然您可能不希望在每个新请求上加载控制器,而是加载(需要)一次,并在每次请求时调用它:

app = require('../app');
testController = require('../controllers/test.js');

app.get('/test', function(req, res, next) {
    // Passing the req, res, next arguments on to your controller allows it to respond
    // i.e. res.json({msg: 'hello world'}).
    testController(req, res, next);
});

如果你直接将这些参数传递给控制器​​(就像你应该的那样),你可以更简洁地写出来:

app = require('../app');
testController = require('../controllers/test.js');

// Call your controller, automatically passing 'req', 'res', 'next' arguments. 
app.get('/test', testController);

有关自动安装路线的完整示例,请结帐:Express MVC example