首页 > 解决方案 > 无法在css中加载背景图像

问题描述

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

文件夹外观:

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

在此处输入图像描述

索引.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 样式的背景图像的方式

主页.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)

标签: csspathfrontendbackground-imagestatic-files

解决方案


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

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

代替

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

这解决了问题。


推荐阅读