简体   繁体   English

使用默认路由的Express.js路由

[英]Express.js routing with default route

I have the following Express.js code: 我有以下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);

It works good. 效果很好。 I don't set path for '/' route in my controllers, and my Express.js server renders 'index.html' from 'public' folder by default - this is what I want. 我没有在控制器中设置'/'路由的路径,默认情况下,我的Express.js服务器从'public'文件夹中渲染'index.html'-这就是我想要的。 Now I want to add '*' route, so Express.js return 'index.html' from 'public' folder - it's static file, no need to render, just returning. 现在,我想添加“ *”路由,因此Express.js从“ public”文件夹返回“ index.html”-这是静态文件,无需渲染,只需返回即可。 How can i do it? 我该怎么做? Thanks 谢谢

If you want your service to serve up public/index.html from your root path you can simply use express.static like this: 如果您希望您的服务从根路径提供public/index.html ,则可以像下面这样简单地使用express.static

app.use(express.static('public'));

express.static will treat index.html as your index file by default, and you can configure this in the 2nd argument: 默认情况下,express.static将把index.html当作索引文件,您可以在第二个参数中进行配置:

app.use(express.static('public', {index: 'myIndex.html'}))

Note also that you don't have to specify the root to app.use the way you are. 还要注意,您不必指定app.use即可。 Simply do this: 只需执行以下操作:

app.use(router);

I would even suggest that your route.controller() methods are not necessary. 我什至建议您route.controller()方法。 If each of your controllers exported their own express.Router() you could simply do app.use(myController) in your iterator. 如果每个控制器都导出了自己的express.Router() ,则只需在迭代器中执行app.use(myController)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM