Skip to content

Instantly share code, notes, and snippets.

@boutell
Created December 31, 2012 22:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boutell/4423473 to your computer and use it in GitHub Desktop.
Save boutell/4423473 to your computer and use it in GitHub Desktop.
express.static middleware must be added before any routes are added to the project, which is potentially confusing when constructing reusable modules to be added to projects as needed. I wish app.use() behaved as just another route for precedence purposes
// HOPED-FOR BEHAVIOR: both /cats.txt AND /cats/cats.txt say: Cats Static
// ACTUAL BEHAVIOR: /cats.txt says Cats Static, but /cats/cats.txt says: Main Wildcard
var express = require('express');
var fs = require('fs');
var app = express();
// Adding the static middleware at the beginning means it wins out over any routes present
// (but only interferes if the file exists)
app.use(express.static(__dirname + '/static'));
if (!fs.existsSync('./static')) {
fs.mkdirSync('./static');
}
fs.writeFileSync('./static/cats.txt', 'Cats Static');
app.get('/', function(req, res) {
res.send('Main Home');
})
// If this statement is called way up top before any routes are added,
// /cats/cats.txt works as expected
app.use('/cats', express.static(__dirname + '/static'));
// If this wildcard route is removed, /cats/cats.txt works as expected
app.get('/*', function(req, res) {
res.send('Main Wildcard');
});
app.listen(3000);
@pcwSlide
Copy link

pcwSlide commented Jan 22, 2021

Hey, I just got the most bizarre behavior.
Unless I put the static middle ware statement AFTER the get route send ( the default route ) does not work..
What the hell? I'm sure it always worked with the static before the routes..

// create an express app
const express = require("express")
const app = express()

app.get("/", function (req, res) {
console.log("What..")
res.send("Hello World!")
})
// use the express-static middleware
app.use(express.static("public"))

// start the server listening for requests
app.listen(process.env.PORT || 3000,
() => console.log("Server is running on Port 3000..."));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment