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 and /style.css--or better yet, any url that would indicate a file (ending in .xyz)
I tried:
app.get('*', function(req, res) {
res.sendfile(__dirname+'/public/index.html');
};
But that sent down bundle.js with the contents of index.html. How do I do this?
I believe there may be two approaches to solve this goal, 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 would work well with the following approach:
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.
Alternatively, you can leave the file structure as is and use the order in which the routes are defined to accomplish similar behavior:
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');
});