在下面的代码中,我正在验证用户输入的用户名和密码以及我的mongo数据库中的详细信息。如果成功,则重定向到/ main route(index.ejs)。我收到错误: - 回调不是函数。 我是nodejs的新手。我无法弄清楚我收到此错误的位置和原因。
app.js
var express = require('express');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var urlencoder = bodyParser.urlencoded({extended : true});
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://<username>: <password>@ds141434.mlab.com:41434/teacherspro'; // using mLab
app.set('view engine' , 'ejs'); // ejs as view engine
var index = require('./routes/index'); // providing routes
var users = require('./routes/users');
app.set('views', path.join(__dirname, 'views'));
app.use(logger('dev'));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/main', index);
app.use('/users', users);
app.get('/login' , function(req,res,next){ // rendering homepage
console.log('\r');
res.render('login'); // rendering login.ejs
console.log('rendered master page!');
next();
});
MongoClient.connect(url , function(err,db){
if (err) return;
app.post('/login' , urlencoder , function(req,res,next){
app.use(bodyParser.json());
var UserName = req.body.UserName;
var Password = req.body.Password;
db.collection('project1').find({ '$and' : [ {"UserName" : UserName} , {"Password" : Password} ]} , {_id : 0}).forEach(function(pes){ // authenticating username and password
if(true)
{
console.log(pes);
res.redirect('/main');
}
});
});
db.close();
next();
});
app.listen(5050);
module.exports = app;
Index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
MongoClient.connect(url , function(err,db){
if (err) return;
db.collection('project1').find({"UserName" : "karan"} , {_id : 0}).forEach(function(pes){
console.log(pes);
res.render('index', {Name : pes});
});
});
});
module.exports = router;
login.ejs
<form id = 'login' method = POST action = '/login'>
<label for = 'Username'> UserName </label>
<input type = 'text' name = 'UserName' value = ''>
<br />
<label for = 'Password'> Password </label>
<input type = 'password' name = 'Password' value = ''>
<br />
<center> <input type ="submit" value = "submit" /> </center>
<br />
</form>