![](/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.