【问题标题】:Express.js Serving Static Files on Dynamic RouteExpress.js 在动态路由上提供静态文件
【发布时间】:2020-08-03 10:01:27
【问题描述】:

我有以下 app.js 代码;

app.use(express.static(__dirname + "/public"));
app.use("/example", express.static(__dirname + "/public"));

app.engine("html", require("ejs").renderFile);

app.get("/", (req, res) => res.render("index.ejs"));
app.get("/example", (req, res) => res.render("example.ejs"));

app.get("/example/:id", (req, res) =>
  res.render("exampleView.ejs", {
    id: req.params.id,
  })
);

在我的 exampleView.ejs 文件中,如果我使用以下图像标签,它可以工作

<img src="/SampleImage.jpg">

但是,如果我在没有/ 的情况下使用它,它将无法工作。使用它不是一个选项,因为它会破坏其他包含的视图文件。

我怀疑第二行是问题,所以我尝试了以下替代方案,

app.get("/example", (req, res) => res.render("example.ejs"));
app.get("/example/*", (req, res) => res.render("/example.ejs"));
app.get("/example", (req, res) => res.render("/*/example.ejs"));

但还是不行。

【问题讨论】:

  • 那么这里的问题是什么?斜线不好吗?
  • 没错,就像我在答案中提到的那样,它确实破坏了渲染结构。我将程序的常用部分导入到其他部分中。
  • 我的意思是,如果你将静态路由设置为/public,所有使用斜线引用资源的内容都类似于http://whataver.com:port/public/resouce.css

标签: javascript node.js express dynamic routing


【解决方案1】:
<img src="SampleImage.jpg">

将尝试在当前路径中查找图像,在您的情况下为“/example/SampleImage.jpg”,而图像位于“/SampleImage.jpg”中。

app.get("/example/:id", ()=>{}) 

将强制所有文件位于/example/... 中。如果你想动态重定向到那个路径,你可以这样编码:

app.use('*.jpg', (req, res, next) => {
    const subRoutes = req.path.split('/')
    const imageFileName = subRoutes[subRoutes.length - 1]
    res.redirect(`/${imageFileName}`)
})
app.use("/example", express.static(__dirname + "/public"))

您可以删除此行

【讨论】:

    猜你喜欢
    • 2012-07-19
    • 1970-01-01
    • 2017-08-16
    • 2018-09-21
    • 2014-11-24
    • 2021-12-10
    • 2010-11-12
    • 2016-05-28
    • 2017-07-27
    相关资源
    最近更新 更多