I am making a service involving a system where the user gets a free subdomain, like archiebaer.blahblahblah.demo
, and I have a function to get the site config file ( siteconf()
) that contains a key called theme. I want archiebaer.blahblahblah.demo/theme-static/style.css
to use express.static()
to serve a folder based on that theme key.
Eg. app.get('/theme-static', express.static("themes/ABC/theme-static"));
where ABC is the theme name.
Example Scenario: johnsmith
and archiebaer
are both users. John's config file looks something like this: {theme:'retro'}
, and Archie's is {theme:'slate'}
. You can get a user's config file from the express route's request parameter using siteconf(req)
. When I go to /theme-static/style.css
on Archie's website, I should get the file ~/projectfolder/themes/slate/style.css
, and on John's: ~/projectfolder/themes/retro/style.css
.
I assume the code would look something like this:
app.get('/theme-static', function (req, res) {
res.send(express.static('themes/' + siteconf(req).theme + '/theme-static/'));
});
Here was my solution:
app.get('/theme-static/*', function (req, res, next) {
var relurl = req.url.replace("/theme-static/", "");
if (relurl === '') {
//This is so '/theme-static/' without any file after is treated as normal 404.
next();
return;
}
var filePath = "themes/" + siteconf(req).theme + "/theme-static/" + relurl;
if (fs.existsSync(filePath)) {
res.sendFile(path.join(__dirname, filePath));
} else {
res.status(404).send("Invalid File");
}
});
You can simply use something like:
app.use("/theme-static", express.static(path.join(__dirname, "pathToFolder")));
If the file doesn't exist, express will handle the error for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.