【问题标题】:Cannot load background images in css无法在css中加载背景图像
【发布时间】:2021-10-14 09:18:56
【问题描述】:

我正在使用 express 作为后端和 pug 作为模板引擎来构建一个站点。我指定了在浏览器中渲染 pug 所需的所有中间件。

文件夹展望:

index.js 与 public 位于同一目录中

Index.js

//Setting public/static files
app.set(express.static,path.join(__dirname,'public'))

//Setting up view engine
app.set("view engine", "pug");
app.set("views", path.join(__dirname, "public/html"));

app.get("/",(req,res)=>{
    res.render('home.pug') //Renders home.pug which extends index.pug
})

这就是我在 home.css 中应用背景图片的方式,样式为 home.pug

home.css:

.home-container {
  color: red;
  width: 100%;
  height: 100%;
  background-image: url("../images/home_bg.jpeg");
}

我什至使用下面的代码并尝试过

background-image: url("/images/home_bg.jpeg");

在这两种情况下,我都会收到以下错误

GET http://localhost:8080/images/home_bg.jpeg 404 (Not Found)

【问题讨论】:

  • 您是否尝试添加“。”前 ”/”?它会将您带到根目录,然后您可以设置路径。即:背景图像:url(“./images/home_bg.jpeg”);
  • 是的,我试过了。任何获取请求应该是localhost:8080/images/home_bg.jpeg,但它返回的是错误而不是图像。由于 root 是公共的

标签: css path frontend background-image static-files


【解决方案1】:

问题在于提供静态文件。 我用过

app.use(express.static(path.join(__dirname,'public')))

而不是

app.set(express.static,path.join(__dirname,''public))

这解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 2011-11-03
    • 1970-01-01
    相关资源
    最近更新 更多