简体   繁体   English

Express.js 在动态路由上提供 Static 文件

[英]Express.js Serving Static Files on Dynamic Route

I have the following app.js code;我有以下 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,
  })
);

and in my exampleView.ejs file, if I use the following image tag it works在我的 exampleView.ejs 文件中,如果我使用以下图像标签,它可以工作

<img src="/SampleImage.jpg">

However, if I use it without / it won't work.但是,如果我在没有/的情况下使用它,它将无法工作。 Using it is not an option because it breaks the other included view files.使用它不是一个选项,因为它会破坏其他包含的视图文件。

I suspect the second line is the issue so I've tried following alternatives,我怀疑第二行是问题,所以我尝试了以下替代方案,

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

but still no good.但还是不行。

<img src="SampleImage.jpg">

Will try to find the image in current route, which is in your case '/example/SampleImage.jpg', whereas the image resides inside '/SampleImage.jpg'.将尝试在当前路线中查找图像,在您的情况下为“/example/SampleImage.jpg”,而图像位于“/SampleImage.jpg”中。

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

Will force all files to be inside /example/... .将强制所有文件位于/example/...中。 If you want dynamic redirection to that path, you can code like this:如果您想要动态重定向到该路径,您可以编写如下代码:

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

You can remove this line您可以删除此行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM