如何在基于URL的目录路径中使用express.static()?

时间:2019-01-24 21:58:53

标签: node.js express url static

我正在提供一项涉及用户获得免费子域的系统的服务,例如archiebaer.blahblahblah.demo,并且我有一个功能来获取包含称为主题的密钥的站点配置文件(siteconf())。 。我希望archiebaer.blahblahblah.demo/theme-static/style.css使用express.static()为基于该主题键的文件夹提供服务。

例如。 app.get('/theme-static', express.static("themes/ABC/theme-static"));,其中ABC是主题名称。


示例场景:johnsmitharchiebaer都是用户。 John的配置文件如下所示:{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/'));
});

2 个答案:

答案 0 :(得分:0)

这是我的解决方法:

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");
  }
});

答案 1 :(得分:0)

您可以简单地使用以下内容:

app.use("/theme-static", express.static(path.join(__dirname, "pathToFolder")));

如果文件不存在,express将为您处理错误。