Javascript 使用passport进行用户身份验证时,NPM resourceful包与couchdb的连接出现错误

Javascript 使用passport进行用户身份验证时,NPM resourceful包与couchdb的连接出现错误,javascript,node.js,couchdb,passport.js,Javascript,Node.js,Couchdb,Passport.js,我有下面的JavaScript代码,它试图通过resourceful连接到CouchDB,以便为passport用户身份验证创建一个用户数据库模型。在this.use('couchdb')行出现错误如下所示: 错误 应请求。_onResponse[作为回调](/home/ict/Documents/hookahDB/serverjs/node_modules/bradle/lib/bradle.js:232:29) at Request.self.callback(/home/ict/Docum

我有下面的JavaScript代码,它试图通过
resourceful
连接到
CouchDB
,以便为
passport
用户身份验证创建一个用户数据库模型。在
this.use('couchdb')行出现错误如下所示:

错误

应请求。_onResponse[作为回调](/home/ict/Documents/hookahDB/serverjs/node_modules/bradle/lib/bradle.js:232:29)

at Request.self.callback(/home/ict/Documents/hookahDB/serverjs/node_modules/Request/Request.js:186:22)

两点钟(events.js:106:13)

at Request.emit(events.js:191:7)

应要求。(/home/ict/Documents/hookahDB/serverjs/node_modules/request/request.js:1081:10)

在emitOne(events.js:96:13)

at Request.emit(events.js:188:7)

在收到消息时。(/home/ict/Documents/hookahDB/serverjs/node_modules/request/request.js:1001:12)

在IncomingMessage.g(events.js:292:16)

在emitNone(events.js:91:20)

//使用了NPM express软件包
//特快专递包裹看起来像一条快车道,可以很快到达目的地
//它是低级HTTP调用之上的高级层
var express=require('express')
var app=express()
//node.js循环正在运行和侦听的端口:
//在主机上,要访问node.js,我们需要使用web浏览器访问以下地址:
//http://127.0.0.1:10002/
const port=process.env.port | | 10002
//为了从POST请求主体中检索HTML5表单输入文本,我们需要NPM`body parser`包
//稍后,我们需要从HTML5表单中检索用户名和密码
//下面是“json”和“urlencoded”之间的区别:

//假设POST:name=foo&color=red我最终使用了
tradle
而不是
resourceful
来使用couchdb

//NPM express package is employed
//express package looks like an express lane which takes you to your destination very fast
//it is a high-level layer on top of low-level HTTP calls
var express = require('express')
var app = express()

//the port at which node.js loop is running and listening:
//on our host machine to access the node.js we need to go to the following address with a web browser:
//http://127.0.0.1:10002/
const port = process.env.PORT || 10002

//to retrieve HTML5 form input texts from body of POST request, we need NPM `body-parser` package
//later on, we need to retrieve username & password from HTML5 form
//here is the difference between `json` and `urlencoded`:
// assuming POST: name=foo&color=red            <-- URL encoding
// or       POST: {"name":"foo","color":"red"}  <-- JSON encoding
var bodyParser = require('body-parser');
app.use(bodyParser.json()); //to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
    extended: true
}));

//public directory from which we are serving the static files
//CSS3 stylesheets are located in `public` directory
//files which are absolutely static without any dynamic content would be in `public`
app.use(express.static(__dirname + '/public'))

//template engine: EJS
//EJS is a template engine which preserves HTML5 syntax and is very popular
//I like to work with HTML5 syntax which is familiar, therefore I choose EJS
app.set('view engine', 'ejs');

//homepage url at '/'
//this is the url of our homepage at which username and password is asked
app.get('/', function(req, res) {
    res.render('index.ejs');
})

//NPM package passport is used as the user-authentication method
//passport is very popular now
var passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy;

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

//middleware: some middleware is required to initialize passport:
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(session({
    secret: 'secret',
    name: 'session id',
    saveUninitialized: true,
    resave: true
}));

//The user id (we provide as the second argument of the done function) is saved in the session and is later used to retrieve the whole object via the deserializeUser function.
//serializeUser determines, which data of the user object should be stored in the session
//The result of the serializeUser method is attached to the session as req.session.passport.user = {}
//Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id:'xyz'}
passport.serializeUser(function(user, done) {
    //done(null, user.id);
    done(null, user._id);
});
//
passport.deserializeUser(function(id, done) {
    /*User.findById(id, function(err, user) {
        done(err, user);
    });*/
    User.find({ _id: id }, function(err, user) {
        if (err || user.length == 0)
            done(err, null);
        else
            done(err, user[0]);
    });
});

//a user data model is needed
//we are going to use CouchDB based on our preliminary studies on tech-selection
//NPM resourceful package has a simplified data-model-management which supports CouchDB
//We are going to use resourceful package
var resourceful = require('resourceful');
resourceful.use('couchdb', { database: 'passport-test' });
var User = resourceful.define('user', function() {
    //specify a storage engine
    //error happens at this line:
    //When uncommenting this line, the above-mentioned error won't happen:
    this.use('couchdb');
    //specify some properties with validation
    this.string('username');
    this.string('password');
    //we don't need `id` since CouchDB assigns an `_id` to every document
    //this.number('id');
    // Specify timestamp properties
    //I'm not sure how timestamp works, but API documentations are using it
    this.timestamps();
})

//we need to define a local Strategy to authenticate with username and password
passport.use(new LocalStrategy(

    function(username, password, done) {
        process.nextTick(function() {
            User.find({
                username: username
            }, function(err, user) {
                if (err) {
                    return done(err);
                }
                if (!user || user.length == 0) {
                    return done(null, false, {
                        message: 'Incorrect username: ' + username
                    });
                }
                user = user[0];
                if (user.password != password) {
                    return done(null, false, {
                        message: 'Incorrect password.'
                    });
                }
                return done(null, user);
            });
        })
    }
));

//login page url at '/login'
//after asking username & password by HTML5 form, user is redirected to `/login` url
app.post('/login',
    passport.authenticate('local', {
        successRedirect: '/profile',
        failureRedirect: '/',
        failureFlash: true
    })
);

//When user can log in, he/she will be going to `/profile` url
app.get('/profile', function(req, res) {
    res.render('profile.ejs')
})

//run nodejs loop to be listening at port number specifiled at the top of the code
app.listen(port, function(err) {
    if (err) {
        throw err
    }
    console.log('server is listening on ' + port + ' ...')
})