Configure Express to send index.html for every url EXCEPT those ending in .css and .js

前端 未结 2 1652
刺人心
刺人心 2020-12-31 05:40

I\'m new to Express and I\'m trying to set up a SPA where every url is handled by index.html (Backbone).

I want every url to send down index.html, except /bundle.js

2条回答
  •  再見小時候
    2020-12-31 06:16

    I managed to solve it this way:

    const getExtension = fileName => (
      fileName.substr(fileName.lastIndexOf('.') + 1)
    )
    
    app.get('*', ({ url }, res) => {
      let filePath
      if (['js', 'css', 'png', 'jpg'].includes(getExtension(url))) {
        filePath = __dirname + '/public/' + url
      } else {
        filePath = __dirname + '/public/' + url + '/index.html'
      }
      res.sendFile(filePath)
    });
    

提交回复
热议问题