【Windows】 express-session + connect-mongo + mongoose 下session问题

最近在 《Node.js + MongoDB + AugularJS Web开发 》知道下学习,在第26章 将用户添加到你的网站章节下,一行一行的输入代码,负责监听的和作为服务器的js文件代码如下:

var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var mongoStore = require('connect-mongo')({session: expressSession});
var mongoose = require('mongoose');
require('./models/users_model.js');
var conn = mongoose.connect('mongodb://localhost/myapp');
var app = express();
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(expressSession({
  secret: 'SECRET',
  cookie: {maxAge: 60*60*1000},
  store: new mongoStore({
      db: mongoose.connection.db,
      collection: 'sessions'
    })
  }));
require('./routes')(app);
app.listen(80);

 

原本以为很顺利,一启动各种错误,最后一只纠结在

cannot connect to server的问题下,我开始是认为是 mongoose没链接上,结果单独用在一个js测试mongoose是可以链接上的。

C:\Program Files\nodejs\myshop\node_modules\connect-mongo\lib\connect-mongo.js:1
33
          throw err;
          ^
 MongoError: cannot connect to server
    at Collection.listIndexes (C:\Program Files\nodejs\myshop\node_modules\mongo
db\lib\collection.js:1712:11)
    at indexInformation (C:\Program Files\nodejs\myshop\node_modules\mongodb\lib
\db.js:1531:25)
    at Db.indexInformation (C:\Program Files\nodejs\myshop\node_modules\mongodb\
lib\db.js:1498:44)
    at ensureIndex (C:\Program Files\nodejs\myshop\node_modules\mongodb\lib\db.j
s:1003:8)
    at Db.ensureIndex (C:\Program Files\nodejs\myshop\node_modules\mongodb\lib\d
b.js:982:44)
    at ensureIndex (C:\Program Files\nodejs\myshop\node_modules\mongodb\lib\coll
ection.js:1772:13)
    at Collection.ensureIndex (C:\Program Files\nodejs\myshop\node_modules\mongo
db\lib\collection.js:1760:44)
    at connectionReady (C:\Program Files\nodejs\myshop\node_modules\connect-mong
o\lib\connect-mongo.js:141:27)
    at Db.collection (C:\Program Files\nodejs\myshop\node_modules\mongodb\lib\db
.js:425:20)
    at initWithNativeDb (C:\Program Files\nodejs\myshop\node_modules\connect-mon
go\lib\connect-mongo.js:207:20)
    at doNTCallback0 (node.js:419:9)
    at process._tickCallback (node.js:348:13)
    at Function.Module.runMain (module.js:469:11)

头疼啊,这样我就只能理解为 connect-mongo 和 express-session上的问题,然后google到 connect-mongo插件的官网:https://www.npmjs.com/package/connect-mongo

Express or Connect integration
Express 4.x, 5.0 and Connect 3.x:

var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
 
app.use(session({
    secret: 'foo',
    store: new MongoStore(options)
}));
Express 2.x, 3.x and Connect 1.x, 2.x:

var MongoStore = require('connect-mongo')(express);
 
app.use(express.session({
    secret: 'foo',
    store: new MongoStore(options)
}));
For Connect 1.x and 2.x, just replace express by connect.

Connection to MongoDB
In many circumstances, connect-mongo will not be the only part of your application which need a connection to a MongoDB database. It could be interesting to re-use an existing connection.

Alternatively, you can configure connect-mongo to establish a new connection.

Re-use a Mongoose connection
var mongoose = require('mongoose');
 
// Basic usage 
mongoose.connect(connectionOptions);
 
app.use(session({
    store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
 
// Advanced usage 
var connection = mongoose.createConnection(connectionOptions);
 
app.use(session({
    store: new MongoStore({ mongooseConnection: connection })
}));
Re-use a native MongoDB driver connection
In this case, you just have to give your Db instance to connect-mongo. If the connection is not opened, connect-mongo will do it for you.

/*
** There are many ways to create dbInstance.
** You should refer to the driver documentation.
*/
 
app.use(session({
    store: new MongoStore({ db: dbInstance })
}));
Create a new connection from a MongoDB connection string
MongoDB connection strings are the best way to configure a new connection. For advanced usage, more options can be configured with mongoOptions property.

// Basic usage 
app.use(session({
    store: new MongoStore({ url: 'mongodb://localhost/test-app' })
}));
 
// Advanced usage 
app.use(session({
    store: new MongoStore({
        url: 'mongodb://user12345:foobar@localhost/test-app?authSource=admins&w=1',
        mongoOptions: advancedOptions // See below for details 
    })
}));

于是修改代码为:标记红色部分

var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var mongoStore = require('connect-mongo')(expressSession);
var mongoose = require('mongoose');
require('./models/users_model.js');
var conn = mongoose.connect('mongodb://localhost:27017/myapp');
var app = express();
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(expressSession({
    resave: false,
    secret: 'SECRET',
    saveUninitialized: true,
    cookie: { maxAge: 60 * 60 * 1000 },
    store: new mongoStore({
        mongooseConnection: mongoose.connection
    })
}));
require('./routes')(app);
app.listen(2016);

再次启动 node auth-server.js
呼呼,就运行起来了。

这个版本问题真的会死人的,所以得多看官方的文档说明啊,真是,。。。。

补【2015-12-28】:
最近跟着node.js实战做 Express + MongoDB搭建多人博客,死活过不去,愁死了。
使用的是 WebStorm 11 ,开始总是提示
Failed to load c++ bson extension, using pure JS version

  气死人了,最后没办法,手动删除所有直接从 WebStorm 11添加的modules,修改package.json文件,

{
  "name": "FirstNodeJSAPP",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "ejs": "~2.3.3",
    "express": "~4.13.1",
    "morgan": "~1.6.1",
    "serve-favicon": "~2.3.0",
    "mongodb":"",
    "express-session":"",
    "connect-mongo":""

  }
}

  关闭WebStorm,在用cmd执行 到目录,执行 npm install,再次运行,呵呵,错误消失,结果出现的错误更改为

 
 
\node_modules\connect-mongo\src\index.js:100
throw new Error(‘Connection strategy not found’);
 
 

  搜索发现https://cnodejs.org/topic/567a1120222744630726b244,有何我们一样的问题,

var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
app.use(session({
secret: settings.cookieSecret,
key: settings.db,//cookie name
cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},//30 days
resave: false,
saveUninitialized: true,
store: new MongoStore({
db: settings.db,
host: settings.host,
port: settings.port
})
}));
 
 

 修改为:

app.use(session({
  secret: settings.cookieSecret,
  key: settings.db,//cookie name
  cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},//30 days
  resave: false,
  saveUninitialized: true,
  store: new MongoStore({
   /* db: settings.db,
    host: settings.host,
    port: settings.port */
    url:'mongodb://'+ settings.host + ':' + settings.port + "/" + settings.db
  })
}));

  

 哎,这只是配置问题,配置问题。。。



你可能感兴趣的:(【Windows】 express-session + connect-mongo + mongoose 下session问题)