简体   繁体   中英

Express.js routing with default route

I have the following Express.js code:

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. 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. 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:

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:

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. Simply do this:

app.use(router);

I would even suggest that your route.controller() methods are not necessary. If each of your controllers exported their own express.Router() you could simply do app.use(myController) in your iterator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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