图片未在 hbs/nodejs 中显示

Images not displaying in hbs/nodejs

我正在尝试使用 NodeJs 和 express-handlebars 创建一个简单的网络应用程序。 但是图像在我使用车把渲染的 html 页面中显示不正确。

下面是我的应用结构

MyApp 是根文件夹

-images
-views
  -layouts
    -main.hbs
  -home.hbs
-index.js
-package.json

project structure

我的index.js包含以下代码

const express = require('express');
const exphbs = require('express-handlebars');

const app = express();

//Setting default layout and extension name
app.engine('hbs', exphbs({
defaultLayout: 'main',
extname: '.hbs'
}));

//providing path for images 
app.use(express.static("images"));

//Setting view engine 
app.set('view engine', 'hbs');

//get method for landing page
app.get('/' , (req , res)=>{
  res.render('landing')
})

//get method for home page
app.get('/home',(req,res) =>{
  res.render('home');
})
//Staring server
app.listen(8080,() =>{
   console.log("Server started successfully on port 8080");
});

home.hbs包含如下

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <img src="/home/vishu/Desktop/WebTest/ECom/images/apple.jpg"  alt="Apple product set">
</body>
</html>

我应该怎么做才能解决上述问题

let options = {
            dotfiles: "ignore", //allow, deny, ignore
            etag: true,
            extensions: ["htm", "html"],
            index: false, //to disable directory indexing
            maxAge: "7d",
            redirect: false,
            setHeaders: function (res: any, path: any, stat: any) {
                //add this header to all static responses
                res.set("x-timestamp", Date.now());
            }
        };

//process.cwd will fetch from the current working directory and serve images over the server
app.use(express.static(`${process.cwd()}/images`, options));
//it will set the html path that would get served from /views 
app.set('views', express.static(process.cwd() + '/views'));
//it will set the engine
app.set('view engine', 'hbs');
        

对于图像 url 使用服务器上的托管图像获取路径。

//BASE URL
`${BASE.URL}/images/Pamlogo.png`
Give it a try, All the best (yes)