[英]Express.js routing with default route
我有以下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);
效果很好。 我沒有在控制器中設置'/'路由的路徑,默認情況下,我的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()
方法。 如果每個控制器都導出了自己的express.Router()
,則只需在迭代器中執行app.use(myController)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.