NodeJS - Express 4.0错误:Cannot read property 'Store' of undefined

按着《NodeJS开发指南》里的第五章建立microblog的例子操作,使用node.js 的express框架配置将session存储到mongodb时出错:TypeError: Cannot read property 'Store' of undefined。

加载connect-mongo模块的写法为:

//加载模块

var MongoStore= require("connect-mongo");

 

//配置express session

app.use(express.session({

   secret:setting.cookieSecret,

   db: seeting.db

})); 

启动程序报错:TypeError: Cannot read property 'Store' of undefined

网上有人修改如下之后重启是OK的:

With express:

    var express = require('express');
    var MongoStore = require('connect-mongo')(express);
 
    app.use(express.session({
        secret: settings.cookie_secret,
        store: new MongoStore({
          db: settings.db
        })
    }));

但是我修改之后报如下错误:

Error: Most middleware (like session) is no longer bundled with Express and must
 be installed separately. Please see https://github.com/senchalabs/connect#middl
eware.
    at Function.Object.defineProperty.get (E:\2014-Study\NoteJS\microblog\node_m
odules\express\lib\express.js:89:13)
    at module.exports (E:\2014-Study\NoteJS\microblog\node_modules\connect-mongo
\lib\connect-mongo.js:30:39)
    at Object.<anonymous> (E:\2014-Study\NoteJS\microblog\app.js:9:42)
    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 Module.require (module.js:364:17)
    at require (module.js:380:17)

后来修改回原来的写法,提示找不到“Store”,然后就到目录“\node_modules\connect-mongo”下查看Readme.md文档,上面提示:

With express4:
    
    var session    = require('express-session');
    var MongoStore = require('connect-mongo')(session);

    app.use(session({
        secret: settings.cookie_secret,
        store: new MongoStore({
          db : settings.db,
        })
      }));

With express<4:

    var express = require('express');
    var MongoStore = require('connect-mongo')(express);

    app.use(express.session({
        secret: settings.cookie_secret,
        store: new MongoStore({
          db: settings.db
        })
      }));

With connect:

    var connect = require('connect');
    var MongoStore = require('connect-mongo')(connect);

因为本机Express的版本是4.0,所以修改成用第一种方式引用session,同时修改目录下的package.json文件,添加对“express-session”的依赖如下:

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "express": "~4.0.0",
    "static-favicon": "~1.0.0",
    "morgan": "~1.0.0",
    "cookie-parser": "~1.0.1",
    "body-parser": "~1.0.0",
    "debug": "~0.7.4",
    "ejs": "~0.8.5",
    "mongodb": ">= 0.9.9",
    "connect-mongo": ">= 0.1.7",
    "express-session": "~1.0.4"
  }
}

然后在命令行下进入到当前目录,执行npm install就默认安装了express-session模块了。

之后再执行npm start启动服务,问题就解决了。

 

 

posted @ 2014-05-05 16:32  linyujade  阅读(9335)  评论(0编辑  收藏  举报