我认识一些JS,但我是Node.js的新手。我知道这是一个非常常见的错误,但我找不到错误的来源,因为我缺乏Node.js的调试技巧。 这是我的app.js:
var index = require('./routes/index');
var users = require('./routes/userlist');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/userlist', users);
这是我的userlist.js:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
这是我的index.js:
var express = require('express');
var router = express.Router();
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
console.log(collection);
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
这是用户列表视图:
extends layout
block content
h1.
User List
ul
each user, i in userlist
li
a(href="mailto:#{user.email}")= user.username
如果您告诉我问题所在,或者告诉我如何发现问题,我感谢您。提前谢谢。
修改
在控制台中,我得到了这个:
GET /userlist 500 296.280 ms - 1501
编辑2: 它给了我这一行的错误:
var collection = db.get('usercollection');
编辑3: 在index.js中,我看到了
router.get('/userlist', function(req, res) {
var db = req.db;
req.db
未定义。为什么不定义?你有什么想法吗?
答案 0 :(得分:3)
将代码更改为有效:
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/', index);
app.use('/userlist', users);
答案 1 :(得分:1)
相应地更改您的代码:
userlist.js
var express = require('express').Router();
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
index.js
var express = require('express').Router();
var router = express.Router();
router.get('/userlist', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
console.log(collection);
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
});
您应该使用var router = require('express').Router();
代替var router = require('express');