NodeJS - Express4.0錯誤:Cannot read property 'Store' of undefined


Express在使用mongodb的時候app配置出錯node

//settings.jsmongodb

module.exports={數據庫

   cookieSecret:"xxxx",express

   db:"dbname",npm

   host:"localhost",
json

}
cookie


//app.js
session

var express = require("express");app

var settings = require("./settings");ui


載入connect-mongo的出錯寫法:

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

app.use(express.session({
    secret:Settings.cookieSecret,
    key:Settings.db,
    cookie:{maxAge:1000*60*60*24*30},//30 days
    store:new MongoStore({
        db:Settings.db
    })
}));

啓動後報錯:TypeError: Cannot read property 'Store' of undefined

以上是 express<4的寫法


express 4.0以後(包含4.0)寫法例如如下:

var session = require("express-session");

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

app.use(session({

   secret:settings.cookieSecret,

   store:new MongoStore({

      db:settings.db

   })

});


package.json配置例如如下

{
  "name": "dbTest",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "express": "~4.2.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":"*",
    "connect-mongo":"*",
    "express-session":"*"
  }
}

//假設文件夾下沒有運行過npm install請在添加mongodb,connect-mongo,express-session以後在package.json文件夾下運行一下npm install

以上是express中對mongodb的配置,假設你本地沒有裝mongodb的數據庫請到http://www.mongodb.org/downloads下載安裝。

相關文章
相關標籤/搜索