【问题标题】:How do display images from the nodejs server如何显示来自 nodejs 服务器的图像
【发布时间】:2022-01-20 04:17:00
【问题描述】:

我必须显示存储在服务器中的图像,图像存储在数据库中,如下所示:

    {"_id":{"$oid":"61bc353829247781224cd5b0"},
    "name":"Chicken Breast",
    "type":"protein",
    "image":"https://mmr-allapi.herokuapp.com/allfoodapi/fooduploads\\Pollo.png",  
     "__v":0}

这条路线的post请求是这样的:

foodrouter.post('/addprotein',upload.single('image'),(req,res,next)=>{

const protein = new Protein({
    _id:mongoose.Types.ObjectId(),
    name:req.body.name,
    type:req.body.type,
    image:"https://mmr-allapi.herokuapp.com/allfoodapi/"+req.file.path
    // image:"localhost:5000/allfoodapi/"+req.file.path
});
protein.save().then(result=>{
    res.status(201).json({
        message:"Protein added"
    })
})
.catch(err=>{
    res.status(500).json({
        error:err
    })
})

});

这是 api 的显示方式

{
"protein": [
{
"name": "Egg",
"type": "protein",
"image": "https://mmr-allapi.herokuapp.com/allfoodapi/fooduploads/Egg.png"
},
{
"name": "Chicken Breast",
"type": "protein",
"image": "localhost:5000/allfoodapi/fooduploads\\Pollo.png"
},
{
"name": "Chicken Breast",
"type": "protein",
"image": "https://mmr-allapi.herokuapp.com/allfoodapi/fooduploads\\Pollo.png"
},
{
"name": "Chicken Breast",
"type": "protein",
"image": "localhost:5000/allfoodapi/fooduploads\\Pollo.png"
},
{
"name": "Chicken Breast",
"type": "protein",
"image": "https://mmr-allapi.herokuapp.com/allfoodapi/fooduploads\\Pollo.png"
}
]
}

这是我显示图像的路线

foodrouter.get("/fooduploads/:str", (req, res) => {
    console.log(req.params.str)
    console.log(req.url)
    res.sendFile(path.join(__dirname, `../fooduploads/${req.params.str}`));
  });

但是这里的问题是当我单击存储在数据库中的图像链接 (https://mmr-allapi.herokuapp.com/allfoodapi/fooduploads\\Pollo.png) 然后我通过图像路由重定向到图像但问题是当我将此链接发送给其他人并且在使用此链接时它说的前端这不起作用

 Cannot GET /allfoodapi/fooduploads//Pollo.png

我该如何解决这个问题,请帮忙

【问题讨论】:

    标签: javascript node.js mongodb multer


    【解决方案1】:

    我看到它是这样存储的:

    {
      "name": "Chicken Breast",
      "type": "Protein",
      "image": "https://images-prod.healthline.com/hlcmsresource/images/AN_images/baked-whole-chicken-1296x728.jpg"
    },
    

    这个链接后面的图片是一个合适的 jpeg,上面有漂亮的烤鸡。您的数据库似乎只保留图像的链接,而不是图像本身。例如,这只特定的鸡存储在 AWS S3 上,其他图像存储在不同的资源上。

    嗯,除了鸡蛋https://mmr-allapi.herokuapp.com/allfoodapi/fooduploads/Egg.png 这个在技术上是可行的,但它看起来不像鸡肉那么好吃。

    【讨论】:

    • 兄弟我的问题是将图像路径存储在数据库中,但是在存储它时存储双反斜杠 (fooduploads\\Egg.png) 并且在存储时我使用了这个前缀 htpps://mmr-allapi。 herokuapp.com/allfoodapi 所以它像这样存储mmr-allapi.herokuapp.com/allfoodapi/fooduploads/Egg.png 但是当我打开它时它可以工作但是当我在我的手机或其他电脑上打开它时它不会工作所以这就是问题
    猜你喜欢
    • 2022-01-19
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    相关资源
    最近更新 更多