我只是在 ExpressJS 中尝试基本路由,到目前为止我有两条路线:
app.get('/', function(req,res) {
res.render('index');
});
app.get('/pics', function(req,res) {
res.render('pics');
});
当这样定义时,在我的 app.js 中,一切正常,但是当按如下方式从我的 routes
子目录中的各个文件导出时,我收到错误消息,表明需要回调函数,但返回了一个 undefined object 。
index.js:
exports.index = function(req,res) {
res.render('index');
});
pics.js
exports.pics = function(req, res) {
res.render('pics');
};
app.js
var routes = require('./routes');
app.get('/', routes.index);
app.get('/pics', routes.pics);
在后一个示例中我做错了什么来破坏一切?
最佳答案
索引路由正在工作,但您的图片路由却不起作用,因为您正在尝试从index.js导入它。
路由目录有index.js,这意味着如果你这样做require('./route')
你实际上在做require('./route/index')
。发生这种情况是因为 index.js 在 Node.js 中具有特殊含义。
因此,要使照片正常工作,您需要执行以下操作:
app.get('/pics', require('./routes/pics').pics);
这确实令人困惑,并且是 IRC channel 上经常被问到的问题。
关于javascript - 从路由目录中的文件导出时,为什么我的 View 没有返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15031374/