我有以下 Express.js 代码:
router = express.Router()
fs.readdirSync('./controllers').forEach(function (file) {
if(file.substr(-3) == '.js') {
route = require('./controllers/' + file);
route.controller(router);
}
});
app.use('/', router);
效果不错。我没有在我的 Controller 中设置 '/' 路由的路径,我的 Express.js 服务器默认从 'public' 文件夹呈现 'index.html' - 这就是我想要的。现在我想添加 '*' 路由,所以 Express.js 从 'public' 文件夹返回 'index.html' - 它是静态文件,不需要渲染,只是返回。我该怎么做?谢谢
最佳答案
如果您希望您的服务从您的根路径提供 public/index.html
,您可以像这样简单地使用 express.static
:
app.use(express.static('public'));
express.static 默认会将 index.html
视为您的索引文件,您可以在第二个参数中进行配置:
app.use(express.static('public', {index: 'myIndex.html'}))
另请注意,您不必按原样指定 app.use
的根目录。只需这样做:
app.use(router);
我什至建议您的 route.controller()
方法不是必需的。如果您的每个 Controller 都导出了它们自己的 express.Router()
,您只需在迭代器中执行 app.use(myController)
。
关于javascript - 使用默认路由的 Express.js 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30556159/