这是 app.js 文件:
var express = require('express'),
routes = require('./routes'),
api = require('./routes/api.js'),
http = require('http'),
path = require('path');
var app= module.exports = express();
/**
* Configuration
*/
// all environments
app.set('port', process.env.PORT || 3001);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
// development only
if (app.get('env') === 'development') {
app.use(express.errorHandler());
}
// production only
if (app.get('env') === 'production') {
// TODO
};
/**
* Routes
*/
// serve index and view partials
app.get('/', routes.index);
// redirect all others to the index (HTML5 history)
app.get('*', routes.index);
api(app);
/**
* Start Server
*/
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
这是routes/api.js 文件:
var queryObj = {
retrieve:{
api_path:'/api/test/list',
var_name:''
}
};
// All supporting functions used below are defined here !
module.exports = function(app) {
_.each(queryObj, function(obj) {
console.log("Check point 1");
var args = [obj.api_path, function(req, res){
var search_term = obj.var_name ? req.params[obj.var_name] : '';
get(search_term,res);
}];
console.log("Check point 2");
console.log("args:" + args);
app.get.apply(app,args);
});
};
这是routes/index.js 文件:
/*
* GET home page.
*/
exports.index = function(req, res){
console.log("Default view");
res.render('index');
};
因此,当我运行此应用程序并在浏览器中输入 localhost:3001/api/test/list 时,我会在控制台上得到以下输出:
检查点1
检查点2
`args: args:/api/alarms/list,函数 (req, res){
var search_term = obj.var_name ? req.params[obj.var_name] : '';
获取(搜索项,res);
}`
Express 服务器监听端口 3001 默认 View
我的问题是:为什么 app.get.apply()
不起作用?相反,app.js 中配置的默认路由被占用!
最佳答案
我认为您需要更改路由定义的顺序:从最具体(在本例中为api/test/list
)到不太具体的*
:
// defined api
api(app);
// serve index and view partials
app.get('/', routes.index);
// redirect all others to the index (HTML5 history)
app.get('*', routes.index);
关于javascript - app..get() 似乎在 Node.js Express 应用程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21620212/