Fairly straightforward problem here: I want to show different HTML based on the subdomain of the user. Here's what I have.
var app = express();
var userapp = connect();
var serveStatic = require("serve-static");
app.use(vhost("*.localhost", userapp));
userapp.get("*", function (req, res, next) {
// Get the subdomain
var subdomain = "";
for (var i = 0; i < req.get("host").length; i++) {
if (req.get("host").charAt(i) === ".") {
subdomain = req.get("host").substring(0, i);
break;
}
}
// Render the proper HTML file based on the subdomain
userapp.use(serveStatic(path.join("./" + subdomain)));
next();
});
app.listen(4242);
Not sure where to go from here, nothing is rendered. Thank you.
The problem is that you want to use serveStatic
dynamically which is not possible. So you can't change your asset folder for each request.
Instead you can dynamically handle requests yourself with something like this:
app.get('/*', function(req, res) {
const fileName =
req.originalUrl === 'http://localhost:4242/index.html' ?
'index.html' : 'notFound.html';
res.sendFile(path.join(__dirname, fileName));
});
You need to manually figure out what is file path depending on URL and subdomain.