I am working on a single page web app using Node + Express and Handlebars for templating. Everything currently works well from index.html, which is served from a pretty standard server.js file:
var express = require('express'); var server = express(); server.use(express.static(__dirname + '/public')); var port = 10001; server.listen(port, function() { console.log('server listening on port ' + port); });
This works perfectly when loading from http://localhost:10001/
. My issue is that I'm using push states in the app, so the browser may show a URL like http://localhost:10001/foo/bar
and then if I refresh the page, I get the error Cannot GET /foo/bar
since there is no route for this.
So my question, and pardon my incredible noobishness when it comes to Node, can I make it so all requests route to index.html? The JavaScript in my app can handle showing the right content based on URL params on page load. I don't want to define custom routes as the number would be large, and the paths for them can change dynamically.
use() function executes middleware in order. The express. static() middleware returns an HTTP 404 if it can't find a file, so that means you should typically call app.
The res. redirect() function redirects to the URL derived from the specified path, with specified status, a integer (positive) which corresponds to an HTTP status code. The default status is “302 Found”.
const express = require('express') const server = express() /* route requests for static files to appropriate directory */ server.use('/public', express.static(__dirname + '/static-files-dir')) /* other routes defined before catch-all */ server.get('/some-route', (req, res) => { res.send('ok') }) /* final catch-all route to index.html defined last */ server.get('/*', (req, res) => { res.sendFile(__dirname + '/index.html'); }) const port = 8000; server.listen(port, function() { console.log('server listening on port ' + port) })
This pattern will serve static assets before hitting the catch-all route that serves up your front-end application. To register any additional routes, just add them above the catch-all route.
var express = require('express'); var server = express(); // middleware server.use(express.static(__dirname + '/public')); // routes server.use('*', function (req, res) { // serve file }); var port = 10001; server.listen(port, function() { console.log('server listening on port ' + port); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With