Nodejs + Mongodb登录示例不起作用

时间:2017-01-23 06:40:53

标签: node.js mongodb

我正在尝试网站http://code.runnable.com/U108R8ihwn4m4TM5/user-creation-signup-and-login-with-express-4-and-mongodb-for-node-js中的代码以及运行

时的代码
  

node server.js

出现以下错误

module.js:340
    throw err;
          ^
Error: Cannot find module 'connect-mongo'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/amitnaik01/Login/server.js:6:18)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)

package.json文件如下:

{
  "name": "ExpressApp",
  "version": "0.0.1",
  "description": "A Node.js App using express",
  "dependencies": {
    "express": "~4.0.0",
    "body-parser": "~1.0.2",
    "express-session": "~1.0.3",
    "express3-handlebars": "~0.5.0",
    "mongodb": "~1.4.2",
    "connect-mongo": "git+https://github.com/kcbanner/connect-mongo.git#master",
    "cookie-parser": "~1.0.1"
  },
  "engine": "node >=0.6.x"
}

server.js文件位于

之下
var express = require('express');
var app = express();
var expressSession = require('express-session');
var expressHbs = require('express3-handlebars');
var mongoUrl = 'mongodb://localhost:27017/dbname';
var MongoStore = require('connect-mongo')(expressSession);
var mongo = require('./mongo');
var port = 8000; // for heroku you would use process.env.PORT instead

// This is a middleware that we will use on routes where
// we _require_ that a user is logged in, such as the /secret url
function requireUser(req, res, next){
  if (!req.user) {
    res.redirect('/not_allowed');
  } else {
    next();
  }
}

// This middleware checks if the user is logged in and sets
// req.user and res.locals.user appropriately if so.
function checkIfLoggedIn(req, res, next){
  if (req.session.username) {
    var coll = mongo.collection('users');
    coll.findOne({username: req.session.username}, function(err, user){
      if (user) {
        // set a 'user' property on req
        // so that the 'requireUser' middleware can check if the user is
        // logged in
        req.user = user;

        // Set a res.locals variable called 'user' so that it is available
        // to every handlebars template.
        res.locals.user = user;
      }

      next();
    });
  } else {
    next();
  }
}

// Use this so we can get access to `req.body` in our posted login
// and signup forms.
app.use( require('body-parser')() );

// We need to use cookies for sessions, so use the cookie parser middleware
app.use( require('cookie-parser')() );

app.use( expressSession({
  secret: 'somesecretrandomstring',
  store: new MongoStore({
    url: mongoUrl
  })
}));

// We must use this middleware _after_ the expressSession middleware,
// because checkIfLoggedIn checks the `req.session.username` value,
// which will not be available until after the session middleware runs.
app.use(checkIfLoggedIn);

app.engine('hbs', expressHbs({extname:'hbs', defaultLayout:'main.hbs'}));
app.set('view engine', 'hbs');

app.get('/', function(req, res){
  var coll = mongo.collection('users');
  coll.find({}).toArray(function(err, users){
    res.render('index', {users:users});  
  })
});

app.get('/login', function(req, res){
  res.render('login');
});

app.get('/logout', function(req, res){
  delete req.session.username;
  res.redirect('/');
});

app.get('/not_allowed', function(req, res){
  res.render('not_allowed');
});

// The /secret url includes the requireUser middleware.
app.get('/secret', requireUser, function(req, res){
  res.render('secret');
});

app.get('/signup', function(req,res){
  res.render('signup');
});

// This creates a new user and calls the callback with
// two arguments: err, if there was an error, and the created user
// if a new user was created.
//
// Possible errors: the passwords are not the same, and a user
// with that username already exists.
function createUser(username, password, password_confirmation, callback){
  var coll = mongo.collection('users');

  if (password !== password_confirmation) {
    var err = 'The passwords do not match';
    callback(err);
  } else {
    var query      = {username:username};
    var userObject = {username: username, password: password};

    // make sure this username does not exist already
    coll.findOne(query, function(err, user){
      if (user) {
        err = 'The username you entered already exists';
        callback(err);
      } else {
        // create the new user
        coll.insert(userObject, function(err,user){
          callback(err,user);
        });
      }
    });
  }
}

app.post('/signup', function(req, res){
  // The 3 variables below all come from the form
  // in views/signup.hbs
  var username = req.body.username;
  var password = req.body.password;
  var password_confirmation = req.body.password_confirmation;

  createUser(username, password, password_confirmation, function(err, user){
    if (err) {
      res.render('signup', {error: err});
    } else {

      // This way subsequent requests will know the user is logged in.
      req.session.username = user.username;

      res.redirect('/');  
    }
  });
});

// This finds a user matching the username and password that
// were given.
function authenticateUser(username, password, callback){
  var coll = mongo.collection('users');

  coll.findOne({username: username, password:password}, function(err, user){
    callback(err, user);
  });
}

app.post('/login', function(req, res){
  // These two variables come from the form on
  // the views/login.hbs page
  var username = req.body.username;
  var password = req.body.password;

  authenticateUser(username, password, function(err, user){
    if (user) {
      // This way subsequent requests will know the user is logged in.
      req.session.username = user.username;

      res.redirect('/');
    } else {
      res.render('login', {badCredentials: true});
    }
  });
});

app.use('/public', express.static('public'));

mongo.connect(mongoUrl, function(){
  console.log('Connected to mongo at: ' + mongoUrl);
  app.listen(port, function(){
    console.log('Server is listening on port: '+port);
  });  
})

无论如何都要解决这个错误?

2 个答案:

答案 0 :(得分:1)

看起来,节点模块中缺少connect-mongo。请安装并保存(将其保存在package.json中只是一种很好的做法)。

npm install connect-mongo --save

或者简单地说,

npm i --s connect-mongo

<强>更新

Syntax error因旧节点版本而异,请输入以下命令来更新Nodejs。

sudo npm cache clean -f
sudo npm install -g n
sudo n stable

答案 1 :(得分:0)

再次安装此模块。

npm install connect-mongo

将其版本更改为最新版本。