Skip to content

Instantly share code, notes, and snippets.

@iamandrewluca iamandrewluca/index.js
Last active Jul 25, 2019

Embed
What would you like to do?
app.get as app.use
const express = require("express");
const app = express();
const staticServe = express.static("public");
function appUse(root, middleware) {
// don't have to do magic
if (!root) {
console.log("no root");
return middleware;
}
return function(req, res, next) {
console.log("INSIDE");
console.log(req.url);
console.log(req.originalUrl);
// don't have to do magic
const noMagic = !req.url.startsWith(root);
console.log(noMagic);
if (noMagic) {
console.error("proxy middleware");
return middleware(req, res, next);
}
// do magic
const savedUrl = req.url;
req.url = req.url.replace(root, "");
function restoreNext() {
console.log("restoreNext");
// req.url = savedUrl;
next.apply(null, arguments);
}
return middleware(req, res, restoreNext);
};
}
const root = "/test";
app.get("*", function(req, res, next) {
console.log("BEFORE");
next();
});
app.get("*", appUse(root, staticServe));
app.get("*", function(req, res, next) {
console.log("AFTER");
console.assert(req.url === req.originalUrl, "req.url was not restored");
next();
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.