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

前端 未结 2 1648
刺人心
刺人心 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:00

    I believe there may be two approaches to solve this goal with the first likely being preferable. If you can move bundle.js and style.css, place them as well as any other static files in the public directory and use the following approach to statically serve all files out of public:

    app.use(express.static(__dirname + '/public'));
    
    app.get('*', function(req, res){
      res.sendfile(__dirname + '/public/index.html');
    });
    

    This approach is preferable because it will "just work" when you place new static files in the public directory. You should then be able to access these static files at http://server:port/bundle.js (or appropriate child folder depending on your chosen hierarchy)

    Alternatively, you can leave the file structure as is and use the order in which the routes are defined to accomplish similar behavior, though it is not quite as flexible and is essentially statically defined:

    app.get('/bundle.js', function(req, res){
      res.sendfile(__dirname + '/bundle.js');
    });
    
    app.get('/style.css', function(req, res){
      res.sendfile(__dirname + '/style.css');
    });
    
    app.get('*', function(req, res){
      res.sendfile(__dirname + '/public/index.html');
    });
    
    0 讨论(0)
  • 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)
    });
    
    0 讨论(0)
提交回复
热议问题