节点抛出TypeError:无法读取未定义的属性'indexOf'

时间:2015-03-26 05:40:30

标签: angularjs node.js express

不确定,但认为我有一些应该有效的东西,但事实并非如此,我得到的错误是无益的。

因此,尝试将护照对象发送到其中一条路线,我理解应该只是设置

var users = require('./routes/users')(app, passport);

在启动时抛出错误

> /Users/bengtbjorkberg/.nvm/versions/node/v0.12.0/bin/node app.js Test
> something 2
> /Users/bengtbjorkberg/WebstormProjects/goMinute/node_modules/express/lib/router/index.js:130
> var search = 1 + req.url.indexOf('?');
>                           ^ TypeError: Cannot read property 'indexOf' of undefined
>     at Function.proto.handle (/Users/bengtbjorkberg/WebstormProjects/goMinute/node_modules/express/lib/router/index.js:130:27)
>     at router (/Users/bengtbjorkberg/WebstormProjects/goMinute/node_modules/express/lib/router/index.js:35:12)
>     at Object.<anonymous> (/Users/bengtbjorkberg/WebstormProjects/goMinute/app.js:41:38)
>     at Module._compile (module.js:460:26)
>     at Object.Module._extensions..js (module.js:478:10)
>     at Module.load (module.js:355:32)
>     at Function.Module._load (module.js:310:12)
>     at Function.Module.runMain (module.js:501:10)
>     at startup (node.js:129:16)
>     at node.js:814:3
> 
> Process finished with exit code 1

如果我删除app和护照,问题就会神奇地消失。 ./routes/users中的溃败还没有使用它们。

我添加了一些代码(删除了一些护照配置以获得良好的形式)

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var stylus = require('stylus');
var nib = require('nib');
var morgan = require('morgan');

//  express session and passport
var session = require('express-session');
var passport = require('passport');
var flash    = require('connect-flash');




var app = express();
function compile(str, path) {
    return stylus(str)
        .set('filename', path)
        .use(nib())
}

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
var accesslevels = require('./config/accesslevels.js');
console.log("Test something " + accesslevels.userRoles.user);
// required for passport
app.use(session({ secret: '' + 'asifIwouldtellstackoverflowright', resave: true, saveUninitialized: true })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

//Routes after passports
var routes = require('./routes/index');
var users = require('./routes/users')(app, passport);
var loginsrv = require('./routes/login');
var api = require('./routes/api');
var partials = require('./routes/partials');

var auth = function(req, res, next) {
    if (!req.isAuthenticated())
        res.send(401);
    else
        next();
    };
//See more at: https://vickev.com/#!/article/authentication-in-single-page-applications-node-js-passportjs-angularjs

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);
app.use('/partials', partials);
app.use('/loginsrv', loginsrv);

//app.use(accesslevels());

//console.log(accesslevels);
// catch 404 and forward 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: {}
    });
});


module.exports = app;
app.listen(30010);

编辑:添加了路由/ users.js

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

/*
// route to test if the user is logged in or not
router.get('/loggedin', function(req, res) {
    res.send(req.isAuthenticated() ? req.user : '0');
});

router.post('/login', passport.authenticate('local'), function(req, res) {
    res.send(req.user);
});

router.post('/logout', function(req, res){
    req.logOut();
    res.send(200);
});
*/

module.exports = router;

在上面的代码中,我使用router.get('/', function(req, res, next)更改了原始router.get('/', function(app, passport, req, res, next),以解决问题。

3 个答案:

答案 0 :(得分:2)

以防万一,如果您在app.use(..)之后使用了任何HTTP动词路由app.get('/'...),那么您将在Express4x中收到此错误。

参考here

答案 1 :(得分:1)

我不确定我理解为什么,但诀窍是用router.get('/', function(req, res, next)更改原始router.get('/', function(app, passport, req, res, next)来解决问题。不确定为什么表达需要一个不使用传递对象的函数来拥有护照和应用程序,但看起来确实如此。

var express = require('express');
    var router = express.Router();

    /* GET users listing. */
    router.get('/', function(app,passport, req, res, next) {
      res.send('respond with a resource');
    });

    /*
    // route to test if the user is logged in or not
    router.get('/loggedin', function(req, res) {
        res.send(req.isAuthenticated() ? req.user : '0');
    });

    router.post('/login', passport.authenticate('local'), function(req, res) {
        res.send(req.user);
    });

    router.post('/logout', function(req, res){
        req.logOut();
        res.send(200);
    });
    */

    module.exports = router;

答案 2 :(得分:0)

app.get('/api',function(req,res)
{
    if (req.url.indexOf('/api')==0) {
        console.log('yes i have done it');
    }
});

我实现了这个,我在控制台上输出。你的代码中发生的是req是未定义的。所以节点抛出了这个错误......正如你在我的代码中看到的那样我们只能使用req .url.indexOf方法只有在我们处于req的范围内时(即你必须在函数回调中声明搜索req,res .....)