使用Pug和expressjs路由,CSS不会显示,图像不会加载,但数据就在那里



只有当我使用路由时才会发生这种情况。

/路由/用户.js

const express = require('express');
const router = express.Router();
const dbQuery = require('../controllers/db_query');
router.get('/', async function(req, res) {
console.log('ROUTE - /');
const result = await dbQuery.getUsers();
res.render('users', {
data: result
});
});
router.get('/:id', async function(req, res) {
console.log('ROUTE - /id');
const result = await dbQuery.getUser(req.params.id);
console.log('result', result);
res.render('user', {
data: result
});
});
module.exports = router;

/App.js

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;

/路由/用户.js

const router = express.Router();
const dbQuery = require('../controllers/db_query');
router.get('/', async function(req, res) {
console.log('ROUTE - /');
const result = await dbQuery.getUsers();
res.render('users', {
data: result
});
});
router.get('/:id', async function(req, res) {
console.log('ROUTE - /id');
const result = await dbQuery.getUser(req.params.id);
console.log('result', result);
res.render('user', {
data: result
});
});
module.exports = router;

/视图/用户.pug

extends layout
block content
// Navigation
nav#mainNav.navbar.navbar-expand-lg.navbar-light.fixed-top
.container
a.navbar-brand.js-scroll-trigger(href='/') Node.js Excersise
button.navbar-toggler.navbar-toggler-right(type='button' data-toggle='collapse' data-target='#navbarResponsive' aria-controls='navbarResponsive' aria-expanded='false' aria-label='Toggle navigation')
| Menu
i.fas.fa-bars
// Masthead
header.masthead
.container.d-flex.h-100.align-items-center
.mx-auto.text-center
h1.mx-auto.my-0.text-uppercase Users List
h2.text-white-50.mx-auto.mt-2.mb-5 This is where you can find all the users.
// Projects
section#projects.projects-section.bg-light
.container
.col-md-10.col-lg-8.mx-auto.text-center
ul
each user in data
div(class='profile-tile')
img(class='img-rounded' src='images/profile/' + user.Uid + '.jpg' alt= user.Uid + ' image')
br
a(class='profile-name' href='/users/' + user.Uid)= user.Uname
li(style='list-style-type:none')= user.Uemail
// Contact
section.contact-section.bg-black
.container
.col-md-10.col-lg-8.mx-auto.text-center
button.btn.btn-primary.mx-auto(onclick="window.location.href='/'") Back
.social.d-flex.justify-content-center
a.mx-2(href='#!')
i.fab.fa-twitter
a.mx-2(href='#!')
i.fab.fa-facebook-f
a.mx-2(href='#!')
i.fab.fa-github
// Footer
footer.footer.bg-black.small.text-center.text-white-50
.container Copyright © : node.js.exercise 2020
// Bootstrap core JS
script(src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js')
script(src='javascript/bootstrap.bundle.min.js')
// Third party plugin JS
script(src='https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js')
// Core theme JS
script(src='javascripts/scripts.js')

下面是我的问题。我试图显示我从数据库获得的数据,并通过路由进行渲染。(请参见h1和img(我得到了预期的结果,但图像(img(没有显示,页面的CSS也没有显示。

顺便说一下,下面的代码与相同/views/users.ug,我只是以更简单的方式显示数据。

/views/user.pug

extends layout
block content
nav#mainNav.navbar.navbar-expand-lg.navbar-light.fixed-top
.container
a.navbar-brand.js-scroll-trigger(href='/') Node.js Excersise
button.navbar-toggler.navbar-toggler-right(type='button' data-toggle='collapse' data-target='#navbarResponsive' aria-controls='navbarResponsive' aria-expanded='false' aria-label='Toggle navigation')
| Menu
i.fas.fa-bars
// Masthead
header.masthead
.container.d-flex.h-100.align-items-center
.mx-auto.text-center
h1.mx-auto.my-0.text-uppercase Users List
h2.text-white-50.mx-auto.mt-2.mb-5 This is where you can find all the users.
// Projects
section#projects.projects-section.bg-light
.container
.col-md-10.col-lg-8.mx-auto.text-center
div(class='profile-tile')
img(class='img-rounded' src='images/profile/' + data[0].Uid + '.jpg' alt='image')
h1= data[0].Uid
h1= data[0].Uname
h1= data[0].Uemail
// Contact
section.contact-section.bg-black
.container
.col-md-10.col-lg-8.mx-auto.text-center
button.btn.btn-primary.mx-auto(onclick="window.location.href='/'") Back
.social.d-flex.justify-content-center
a.mx-2(href='#!')
i.fab.fa-twitter
a.mx-2(href='#!')
i.fab.fa-facebook-f
a.mx-2(href='#!')
i.fab.fa-github
// Footer
footer.footer.bg-black.small.text-center.text-white-50
.container Copyright © : node.js.exercise 2020
// Bootstrap core JS
script(src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js')
script(src='javascript/bootstrap.bundle.min.js')
// Third party plugin JS
script(src='https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js')
// Core theme JS
script(src='javascripts/scripts.js')

/views/layout.js

head
meta(charset='utf-8')
meta(name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no')
meta(name='description' content='')
meta(name='author' content='')
title Node.js
link(rel='icon' type='image/x-icon' href='/images/favicon.ico')
// Font Awesome icons (free version)
script(src='https://use.fontawesome.com/releases/v5.13.0/js/all.js' crossorigin='anonymous')
// Google fonts
link(href='https://fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet')
link(href='https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i' rel='stylesheet')
// Core theme CSS (includes Bootstrap)
link(href='stylesheets/styles.css' rel='stylesheet')
body
block content

我正试图弄清楚为什么当我转到时它没有正确渲染:localhost/users/1

最后,我注意到当我走这条路的时候localhost/users我得到了预期的结果。但如果我在最后加上一个'/'localhost/users/我将遇到上述问题。没有CSS,它没有读取我在应用程序中为我的图像定义的静态:app.use(express.static(path.join(__dirname, 'public')));

我已经学习node.js两周了,我现在正试着用它来学习PUG。

提前谢谢大家。

设法从我的同事那里得到了答案(感谢Kevin(。

问题的原因是,我没有在link(href='stylesheets/styles.css' rel='stylesheet')中放入"/"/views/layout.pug。这会导致浏览器假定路径是相对于文档的。

注意: 这可以在浏览器的网络调试选项卡中进行检查。

当我在localhost:port/users中时,相对路径是可以的,因为当前URL没有"/"。因此样式表将在URL 中工作

localhost:端口/用户

localhost:port/edit

等等…

样式表的相对路径是:localhost:port/stylesheets/styles.css(正确(

但是在路径中遇到"/"时。相对路径将基于其当前位置/URL的路径而改变。

在这种情况下。

例如

localhost:port/users/

localhost:port/users/1

localhost:port/edit/abc

样式表现在将相对于上面的这些路径或文档路径:

localhost:port/users/stylesheets/styles.css(不正确(

FIX

如果我们将"/"放在开头,浏览器将查找相对于网站根的页面(称为绝对URL(。

我也从这个问题中得到了一些想法:https://github.com/pugjs/pug/issues/2662

最新更新