![](/img/trans.png)
[英]How do I use session and cookies for express.use(express.static('static'))?
[英]How do I use express.static() with a directory path based on the URL?
我正在提供涉及用户可获取免费子域的系统的服务,例如archiebaer.blahblahblah.demo
,并且我有一个函数来获取包含名为主题的密钥的站点配置文件( siteconf()
)。 我希望archiebaer.blahblahblah.demo/theme-static/style.css
使用express.static()
服务基于该主题键的文件夹。
例如。 app.get('/theme-static', express.static("themes/ABC/theme-static"));
其中ABC是主题名称。
示例场景: johnsmith
和archiebaer
都是用户。 约翰的配置文件看起来像这样: {theme:'retro'}
,而Archie的配置文件是{theme:'slate'}
。 您可以使用siteconf(req)
从快速路由的请求参数中获取用户的配置文件。 当我访问Archie网站上的/theme-static/style.css
时,我应该获得文件~/projectfolder/themes/slate/style.css
以及John的文件: ~/projectfolder/themes/retro/style.css
。
我认为代码看起来像这样:
app.get('/theme-static', function (req, res) {
res.send(express.static('themes/' + siteconf(req).theme + '/theme-static/'));
});
这是我的解决方案:
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");
}
});
您可以简单地使用类似:
app.use("/theme-static", express.static(path.join(__dirname, "pathToFolder")));
如果文件不存在,express将为您处理错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.