MEAN API,未定义不是一个函数

时间:2015-08-14 14:45:02

标签: node.js express mongoose mean

我正在尝试实现一个简单的API但是当我导航到api / users时,获取undefined不是一个函数。花了好几个小时试图解决这个问题,我们将非常感谢任何建议。

堆栈跟踪

TypeError: undefined is not a function
   at module.exports (//config/routes.js:10:9)
   at Layer.handle [as handle_request] (/node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (/node_modules/express/lib/router/index.js:312:13)
   at /U/node_modules/express/lib/router/index.js:280:7
   at Function.process_params (//node_modules/express/lib/router/index.js:330:12)
   at next (//node_modules/express/lib/router/index.js:271:10)
   at logger (//node_modules/morgan/index.js:144:5)
   at Layer.handle [as handle_request] (/U/node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (//node_modules/express/lib/router/index.js:312:13)
   at //node_modules/express/lib/router/index.js:280:7
   at Function.process_params (//node_modules/express/lib/router/index.js:330:12)
   at next (//node_modules/express/lib/router/index.js:271:10)
   at SessionStrategy.strategy.pass (//node_modules/passport/lib/middleware/authenticate.js:318:9)
   at SessionStrategy.authenticate (//node_modules/passport/lib/strategies/session.js:67:10)
   at attempt (//node_modules/passport/lib/middleware/authenticate.js:341:16)
   at authenticate (//node_modules/passport/lib/middleware/authenticate.js:342:7)

我有以下设置。

app.js

'use strict';
var express = require('express');
var env     = 'development';
var app     = express();
var config  = require('./config/config')[env];

require('./config/mongoose')(config);
require('./config/express')(app, config);
require('./config/passport')();
require('./config/routes')(app);

app.listen(config.port, function() {
    console.log('Express server listening on port ' + config.port);
    console.log('env = ' + app.get('env') +
                '\n__dirname = ' + __dirname  +
                '\nprocess.cwd = ' + process.cwd());
}

express.js

/* jshint -W117 */
var express    = require('express'),
    logger     = require('morgan'),
    bodyParser = require('body-parser'),
    favicon    = require('serve-favicon'),
    cookieParser = require('cookie-parser'),
    env     = 'development',
session    = require('express-session'),
    passport   = require('passport'),
    four0four  = require('../utils/404')();

module.exports =  function(app, config) {

    app.use(favicon(config.rootPath + '/favicon.ico'));
    app.use(cookieParser());
    app.use(bodyParser.urlencoded({extended: true}));
    app.use(bodyParser.json());
    app.use(session({resave: false, saveUninitialized:false,
                     secret: 'all is well that ends well'}));
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(logger('dev'));
    app.use('/api', require('./routes'));

    console.log('About to crank up node');
    console.log('PORT=' + config.port);
    console.log('NODE_ENV=' + env);

    switch (env){
        case 'production':
            console.log('** BUILD **');
            app.use(express.static('./build/'));
            // Any invalid calls for templateUrls are under app/* and should return 404
            app.use('/app/*', function(req, res, next) {
                four0four.send404(req, res);
            });
            // Any deep link calls should return index.html
            app.use('/*', express.static('./build/index.html'));
            break;
        default:

            console.log('** DEV **');

            app.use(express.static('./src/client/'));
            app.use(express.static('./'));
            app.use(express.static('./tmp'));
            // Any invalid calls for templateUrls are under app/* and should return 404
            app.use('/app/*', function(req, res, next) {
                four0four.send404(req, res);
            });
            // Any deep link calls should return index.html
            app.use('/*', express.static('./src/client/index.html'));
            break;
    }
}

routes.js

var four0four = require('../utils/404')(),
    auth      = require('../config/auth'),
    users     = require('../controllers/users'),
    mongoose  = require('mongoose'),
    User      = mongoose.model('User');

module.exports = function(app) {

    app.get('/users', auth.requiresRole('admin'), users.getUsers);
    app.post('/users', users.createUser);
    app.put('/users', users.updateUser);

    app.post('/login', auth.authenticate);
    app.post('/logout', function(req, res) {
        req.logout();
        res.end();
    });
    app.all('/*', four0four.notFoundMiddleware);
}

auth.js

var passport = require('passport');

exports.authenticate = function(req, res, next) {
    req.body.username = req.body.username.toLowerCase();
    var auth = passport.authenticate('local', function(err, user) {
        if (err) {return next(err);}
        if (!user) {res.send({success:false});}
        req.login(user, function(err) {
            if (err) {return next(err);}
            res.send({success:true, user:user});
        });
    });
    auth(req, res, next);
};

exports.requiresApiLogin = function(req, res, next) {
    if (!req.isAuthenticated()) {
        res.status(403);
    } else {
        next();
    }
};

exports.requiresRole = function(role) {
    return function(req, res, next) {
        if (!req.isAuthenticated() || req.user.roles.indexOf(role) === -1) {
            res.status(403);
            res.end();
        } else {
            next();
        }
    };
}

1 个答案:

答案 0 :(得分:0)

我解决这个问题是我的routes.js文件的完整重构。我还从app.js

中删除了这一行
require('./config/routes')(app);

以下是routes.js文件在重构后的样子。

var four0four = require('../utils/404')(),
    auth      = require('../config/auth'),
    users     = require('../controllers/users'),
    mongoose  = require('mongoose'),
    User      = mongoose.model('User'),
    router    = require('express').Router();



router.get('/users', auth.requiresRole('admin'), users.getUsers);
router.post('/users', users.createUser);
router.put('/users', users.updateUser);
router.post('/login', auth.authenticate);
router.post('/logout', logoutUser);
router.all('/*', four0four.notFoundMiddleware);

module.exports = router;
//////////////
function logoutUser (req, res){
    req.logout();
    res.end();
}