【问题标题】:How to serve images as static files using url parameters in express js?如何使用 express js 中的 url 参数将图像作为静态文件提供?
【发布时间】:2022-11-04 02:51:05
【问题描述】:

我正在尝试根据用户输入的参数从我的项目中的“图像”文件中提供图像。

例如,

https://localhost:3000/images?fileName=burger

应该在浏览器上显示图像

有谁知道我该怎么做?

我试图这样做,但由于某种原因它不起作用

app.use('/images', express.static('images'));
if(req.query.fileName === "burger"){
      res.sendFile("burger.jpg" , {root: path.join("./images")});
}

【问题讨论】:

  • 你能分享你的文件结构树吗?将帮助我们更好地理解它。谢谢你

标签: javascript node.js image api express


【解决方案1】:

根据您的代码,如果您的文件结构如下。您的代码将完美运行。确保您在 express.static() 下设置了提供静态文件的路径,并注意您的传入查询值与您需要获取的文件完全匹配,包括案例。这应该可以解决问题,谢谢!

File Structure: 

images 
  --- burger.jpg
index.js
import express from 'express';
import path from 'path'

const app = express();
const PORT = process.env.PORT || 5000;

app.use('/images', express.static('images'));

app.get('/images', (req, res) => {
    if(req.query.filename === 'rocket'){
        res.sendFile("rocket.jpg" , {root: path.join("./images")});
})

app.listen(PORT, () => {
    console.log('Server is up and running on PORT: ${PORT}');
})

【讨论】:

    猜你喜欢
    • 2017-10-20
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 2013-12-26
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    相关资源
    最近更新 更多