Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node + Express with static HTML. How to route all requests to index.html?

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.

like image 519
JPollock Avatar asked Oct 13 '14 21:10

JPollock


People also ask

What does Express static () return?

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.

Which method enables to redirect a route in Express?

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


2 Answers

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) }) 
like image 135
cdock Avatar answered Sep 24 '22 04:09

cdock


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); }); 
like image 30
Nick Tomlin Avatar answered Sep 26 '22 04:09

Nick Tomlin