【问题标题】:Pug won't display pictures帕格不会显示图片
【发布时间】:2020-12-15 04:03:12
【问题描述】:

我只是想玩一下 express,但我无法理解视图引擎。我没有得到背景图片或任何与此相关的图片。我在 html 中尝试了相同的 css 代码,看起来不错,但在 pug 中它只是空白。

我有以下结构:

-public
--home.jpg
--styles.css
-views
--index.pug 
-main.js

除此之外,视图引擎似乎可以很好地渲染 pug 页面,并将简单的 css 逻辑加载到页面中。

main.js 

const debug = require("debug");
const path = require("path");
const express = require("express");
const app = express();
const dotenv = require("dotenv");
const timeout = require("connect-timeout");
dotenv.config();

//Load View Engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// Home Route
app.get("/", (req, res) => {
  res.render('index');
});

背景图片应该加载图片

index.pug

doctype html
html
  head
    style 
      include ../public/styles.css
    title Basic Website
  body
    .container 
      .background-image
        .header
          h1. 
            The basic website 

当我检查页面时会显示容器和图像的属性,但图像仍然不可见

styles.css

.container{
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}

/*Background image*/
/*****************/
.background-image{
  width:100%;
  height: 100%;
  background: url("home.jpg");
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  position: absolute;
  top: 0;
}  

【问题讨论】:

    标签: css image express pug web-site-project


    【解决方案1】:

    Express JS 不允许提供静态文件,如图像、视频等。静态文件由客户端从服务器下载。然而,如果 我们必须提供静态文件,我们必须启用中间件 专门为此目的。为此,首先我们将创建一个 在我们的项目目录中名为 public 的文件夹或目录,然后添加 index.js 中的以下代码行。

    //use middleware to serve static files
    app.use(express.static('public'));
    

    之后,可以将图片添加到公用文件夹并在 pug 中引用它们:

    img(src="/name.png", alt="picture")

    取自:https://learncybers.com/static-files-in-express-js/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-20
      • 2013-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      相关资源
      最近更新 更多