我正在使用expressjs进行我的第一个项目,我遇到了路由器无法安装的问题。我基本上有app安装路由器对象,然后应该安装第二个路由器对象。第一个嵌入式路由器通过app.use命令成功安装,但第二层嵌入式路由器未由第一层嵌入式路由器安装。我需要比我聪明的人告诉我为什么我的方法不起作用。非常感谢所有帮助。
请参阅下面的项目详情和代码段。
app.js
var express = require('express');
var app = express();
//path to db controller and model scripts
app.set('dbPath','/db');
//build connect string
var host='localhost'
var port='27017';
var dbName = 'Reckon_Orbs';
app.set('dbConnectString','mongodb://'+host+':'+port+'/'+dbName);
var dbRouterMod = require('./routes/db/db_router.js');
var dbRouterContainer = new dbRouterMod(express,app.get('dbPath'),app.get('dbConnectString'));
app.use('/db', dbRouterContainer.dbRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
db_router.js
var DbRouter = function(express,dbPath,connectString) {
this.dbRouter = express.Router();
var userRouterMod = require('./user_router.js');
var userRouterContainer = new userRouterMod(express,dbPath,connectString);
//this.dbRouter.get('/user',function(req,res){res.send("hello")});
this.dbRouter.use('/user',userRouterContainer.userRouter);
console.log("db_router instantiated");
};
module.exports = DbRouter;
user_router.js
var UserRouter = function(express,dbPath,connectString){
this.userRouter = express.Router();
this.userRouter.get('/get',function(req,res){res.send("hello")});
console.log("user_router instantiated");
};
module.exports = UserRouter;
当我使用节点www启动节点时,我得到以下输出,表明我的类正在实例化。
C:\NETSHARE\data\devprojects\eclipse\Reckon_Orbs\bin>node www
user_router instantiated
db_router instantiated
Express server listening on port 3000
我打电话时得到的结果:http://localhost:3000/db/user/get
是404错误。但是,如果我在db_router中取消注释注释的代码行并调用http://localhost:3000/db/user
,我会得到" hello"作为回应。这表明第一层嵌入式路由器的安装工作正常。
答案 0 :(得分:1)
让我帮助你如何很好地组织它并使一切正常。
您可以使用 app.js 这样的内容:
var express = require('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 config = require('./config/config');
var mongoose = require("mongoose");
var app = express();
var port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// view engine setup, it can be ejs, jade or whatever you like
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var connect = function(){
var options = {
server: {
socketOptions:{
keepAlive : 1
}
}
};
mongoose.connect(config.db,options);
};
connect();
mongoose.connection.on('error',console.log);
mongoose.connection.on('disconnected',connect);
require('./config/routes')(app);
require('./config/express')(app);
module.exports = app;
<强>配置/ config.js 强>
//you can further break your configuration for different environments such as development, production, test, stating etc.
var path = require("path");
var extend = require("util")._extend;
var development = require("./env/development");
var test = require("./env/test");
var production = require("./env/production");
var defaults = {
root: path.normalize(__dirname + '/..')
};
module.exports = {
development: extend(development,defaults),
test: extend(test,defaults),
production: extend(production,defaults)
}[process.env.NODE_ENV || "development"]
<强>配置/ ENV / development.js 强>
module.exports = {
db: 'mongodb://localhost/MeanDemo_dev'
};
非常整洁,你可以整理你的路线。
<强>配置/ routes.js 强>
var routes = require('../routes/index');
var users = require('../routes/users');
module.exports = function (app){
app.use('/', routes);
app.use('/user',users);
}
路由示例,在我的情况下调用最终与MongoDB交互的控制器。 的路由/ index.js 强>
var express = require('express');
var router = express.Router();
var meetupController = require('../app/controllers/MeetupController');
router.post('/meetup',meetupController.create);
router.get('/meetup',meetupController.getAll);
router.get('/meetup/:id',meetupController.get);
router.put('/meetup/:id',meetupController.update);
router.delete('/meetup/:id',meetupController.delete);
module.exports = router;
我的项目骨架如下:
你可以看看完整的源代码here,如果你想进一步想要Angularjs在前端,这是一个很好的例子。 所以这就是我组织代码的方式,它运行得很好。我希望它也会对你有所帮助。感谢。
答案 1 :(得分:1)
我弄明白了这个问题。如果路由器B尚未安装,则无法将路由器A安装到路由器B.因此,不必在路径路径中自下而上构建路由器模块,而是必须从应用程序开始自上而下构建它们。我将我的代码修改为如下所示,它按预期工作。请注意,我的解决方案是包含一个在安装路由器后安装路由器子路由器的功能。因此调用者必须安装新的路由器,然后调用路由器的executeMount函数,以便在安装链的下游安装任何路由器。该解决方案允许在路由器创建期间依赖注入,这正是我所寻求的。
app.js
var dbRouterMod = require('./routes/db/db_router.js');
var dbRouterContainer = new dbRouterMod(express,app.get('dbPath'),app.get('dbConnectString'));
app.use('/db', dbRouterContainer.router);
dbRouterContainer.executeMounts();
db_router.js
var DbRouter = function(express,dbPath,connectString) {
this.router = express.Router();
console.log("db_router instantiated");
this.executeMounts = function(){
var userRouterMod = require('./user_router.js');
var userRouterContainer = new userRouterMod(express,dbPath,connectString);
this.router.use('/user',userRouterContainer.router);
userRouterContainer.executeMounts();
};
};
module.exports = DbRouter;
user_router.js
var UserRouter = function(express,dbPath,connectString){
this.router = express.Router();
console.log("user_router instantiated");
this.executeMounts = function(){
this.router.get('/get',function(req,res){res.send("hello")});
};
};
module.exports = UserRouter;