首页 > 解决方案 > 使用 Pug 无法在 Express Js 中加载图像

问题描述

我已经仔细检查了路径并一次又一次地检查,但没有在浏览器上加载图像。我正在使用 Pug 引擎模板来为页面提供服务,除了图像没有加载之外,一切看起来都还不错。这是我在 VSC 中的文件结构和代码本身。

在此处输入图像描述

我在 chrome 浏览器上访问的本地主机上得到的输出

在此处输入图像描述

这是我的 app.js 代码

const express = require("express");
const path = require("path");
// const fs = require("fs");
const app = express();
const port = 80;


const express = require("express");
const path = require("path");

const app = express();
const port = 80;


// EXPRESS SPECIFIC STUFF
app.use('/static', express.static('staitc')) // For serving static files
app.use(express.urlencoded())

// PUG SPECIFIC STUFF
app.set('view engine', 'pug') // Set the template engine as pug
app.set('views', path.join(__dirname, 'views')) // Set the views directory

// ENDPOINTS
app.get('/', (req, res)=>{
    // const con = "This is the best content on the internet so far so use it wisely"
    // const params = {'title': 'PUBG is the best game', "constent": con}
    const params = { }
    res.status(200).render('home.pug', params);
})
app.get('/contact', (req, res)=>{
    // const con = "This is the best content on the internet so far so use it wisely"
    // const params = {'title': 'PUBG is the best game', "constent": con}
    const params = { }
    res.status(200).render('contact.pug', params);
})

// START THE SERVER
app.listen(port, ()=>{
    console.log(`The application started successfully on port ${port}`);
});

标签: javascripthtmlnode.jsimagepug

解决方案


我忽略了声明的 2-times express, path, app,port在你的app.js.

介绍一下我的方法。

app.js

  // add under const values
  app.use(express.static(path.join(__dirname, 'static')));

home.pug

  img(src="/img/1.png", alt="Dance...")

推荐阅读