NodeJS module.exports无法按预期工作

时间:2015-11-27 18:24:34

标签: node.js express

我正在使用Express在NodeJS中编写Web服务。当我想在其他模块中使用应用程序(Express实例)时,我的问题就出现了。以下配置工作正常,但如果我替换

var app = module.exports = express();

var app = express();

然后使用

module.exports = app;

在app.js的底部,一切都会崩溃。在auth模块中调用app.get()时会出错(TypeError:app.get不是函数)。有人可以向我解释为什么导出app对象的重要性?

app.js

var mongoose = require('mongoose');
var express = require('express');
var bodyParser = require('body-parser');
var debug = require('debug')('app');
var morgan = require('morgan');
var config = require('./config');
var app = module.exports = express();

// --- globals ---
app.set('jwtTokenSecret', config.jwtTokenSecret);

// --- middleware ---
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(morgan('dev'));

// --- routes ---
var courses = require('./routes/courses');
var users = require('./routes/users');
var auth = require('./routes/auth');

app.use('/auth', auth);
app.use('/courses', courses);
app.use('/users', users);

// --- database connection ---
mongoose.set('debug', true);

mongoose.connect(config.database, function(err) {
    if (err) {
        debug('Could not establish connection to mongodb');
    } else {
        debug('Successfully connected to mongodb');
    }
});

路由/ auth.js

var express = require('express');
var router = express.Router();
var moment = require('moment');
var jwt = require('jwt-simple');
var User = require("../models/User");
var debug = require('debug')('app');
var app = require("../app");

// POST /auth
router.post('/', function(req, res, next) {
    User.findOne({
        'username' : req.body.username
    }, function(err, user) {
        if (err || !user) {
            res.status(401).json({ error: "No user found"});
            return;
        }
        if (user.password != req.body.password) {
            res.send(401);
        }

        debug(app.get('database'));

        var expires = moment().add(7, 'days').valueOf();
        var token = jwt.encode({
            user: user.username,
            exp: expires
        }, app.get('jwtTokenSecret'));

        res.json({
            success: true,
            token: token
        });
    });
});

module.exports = router;

1 个答案:

答案 0 :(得分:4)

这是因为app.js和auth.js之间存在循环依赖关系。

在app.js文件中,您需要auth.js,而在auth.js中,您需要app.js.通过将module.exports = app移到app.js的底部,它被称为AFTER var auth = require('./routes/auth');。这意味着当在auth.js中调用var app = require("../app");时,{app}内部尚未定义module.exports,从而导致错误。