我是Node和Express的新手,所以到目前为止我的知识是有限的。我有Node.js,Express和MongoDB的设置。我正在尝试路由请求" localhost:3000 / v1 / user"通过在我的主.js文件中这样做:
MongoClient.connect(mongoUrl, function (err, db) {
if (err) {
console.log("Unable to connect to the mongoDB server. Error:", err);
} else {
//HURRAY!! We are connected. :)
console.log("Connection established to Mongo DB with connection string " + connection_string);
let port = process.env.NODE_PORT || 3000;
app.listen(port);
console.log('Server is now listening to port ' + port);
app.use(function(req, res){
req.db = db;
console.log("DB now available for all routes");
});
console.log("Using v1");
app.use('/v1', v1Route);
}
});
与mongo的连接建立正常。 我在两个单独的文件中有两个路由器,如下所示:
v1Route:
var express = require('express')
var router = express.Router();
const userRoute = require('./userRoute');
router.use('/user', userRoute);
module.exports = router;
userRoute:
const express = require('express');
var router = express.Router();
router.get('/', function(req,res){
console.log('fetching all users');
var collection = req.db.collection('user');
collection.find().toArray(function (err, result) {
if (err) {
console.log(err);
} else if (result.length > 0) {
console.log('Found entry');
res.status(200).send('Found:' + result[0].firstName + ' ' + result[0].lastName).end();
} else {
console.log('No document(s) found with defined "find" criteria!');
res.status(200).send('No document(s) found with defined "find" criteria!').end();
}
})
});
module.exports = router;
问题是当我尝试发出请求" localhost:3000 / v1 / user"时没有任何反应。我没有错误,只是一个停止的浏览器。当我发送请求时,我得到了日志字符串" DB现在可用于所有路由"。
答案 0 :(得分:2)
在您的中间件功能中,您没有调用next
处理程序,因此未执行下一个中间件:
app.use(function(req, res, next) {
req.db = db;
console.log("DB now available for all routes");
next();
});
您可以在官方express
网站上查看有关编写中间件的更多文档:http://expressjs.com/en/guide/writing-middleware.html
答案 1 :(得分:0)
您必须在app.use之后启动服务器(' / v1',v1Route);
MongoClient.connect(mongoUrl, function (err, db) {
if (err) {
console.log("Unable to connect to the mongoDB server. Error:", err);
} else {
//HURRAY!! We are connected. :)
console.log("Connection established to Mongo DB with connection string " + connection_string);
app.use(function(req, res){
req.db = db;
console.log("DB now available for all routes");
});
console.log("Using v1");
app.use('/v1', v1Route);
let port = process.env.NODE_PORT || 3000;
app.listen(port);
console.log('Server is now listening to port ' + port);
}
});