Created
January 13, 2020 06:30
-
-
Save tilleps/4524f2471c298d084b19a154f588de93 to your computer and use it in GitHub Desktop.
ExpressJS strict routing workaround
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Enforcing strict routing | |
https://github.com/expressjs/express/issues/2281 | |
Use cases: | |
GET /strict -> noslash | |
GET /strict/ -> noslash (expect slash) | |
GET /strict// -> noslash (expect 404) | |
GET /strictslash -> noslash (expect 404) | |
GET /strictslash/ -> noslash | |
GET /strictslash// -> noslash (expect 404 or slash - not sure) | |
GET /strictslash/// -> noslash (expect 404) | |
//*/ | |
const express = require("express"); | |
const app = express(); | |
app.set("strict routing", true); | |
const router = express.Router({ strict: true }); | |
// Middleware to enforce strict URLs | |
router.use(function strict(req, res, next) { | |
if (req.app.get("strict routing")) { | |
req.url = req.originalUrl.substring(req.baseUrl.length); | |
} | |
next(); | |
}); | |
// Note: using .use() will not work: | |
// router.use("", function (req, res, next) { | |
router.all("", function (req, res, next) { | |
res.send("noslash"); | |
}); | |
// Note: using .use() will not work: | |
// router.use("", function (req, res, next) { | |
router.all("/", function(req, res) { | |
res.send("slash"); | |
}); | |
app.use("/strict", router); | |
app.use("/strictslash/", router); | |
app.listen(4000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment