简体   繁体   English

node.js不会在所有页面中加载CSS样式

[英]node.js won't load css styles in all pages

I'm writing a simple blog from scratch to learn node.js + express. 我正在从头开始编写一个简单的博客,以学习node.js + express。 I'm stumped on an issue though, when I try to access a directory that's nested, the styles won't load. 不过,当我尝试访问嵌套的目录时,我很困惑,无法加载样式。 For example: 例如:

app.get('/posts/new', (req, res) => {
  res.render('create')
});

will not use the styles, but simply using '/posts' will. 将不使用样式,而仅使用“ / posts”将。

any idea what's causing this? 知道是什么原因造成的吗? Here's the full code: 这是完整的代码:

const path = require('path');
const expressEdge = require('express-edge');
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = new express();

mongoose.connect('mongodb://localhost:27017/node-blog', {
    useNewUrlParser: true
})
  .then(() => 'You are now connected to Mongo!')
  .catch(err => console.error('Something went wrong', err))

app.use(express.static('public'));
app.use(expressEdge);
app.set('views', __dirname + '/views');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: true
}));

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

app.get('/posts/new', (req, res) => {
  res.render('create')
});

app.post('/posts/store', (req, res) => {
  console.log(req.body)
  res.redirect('/')
});
app.listen(4000)

And here is directory structure: 这是目录结构:

└── node-blog
    ├── database
    ├── node_modules
    ├── public
        ├── css
        ├── img
        ├── vendor
        ├── js
    ├── theme
    └── views
        ├── layouts

all the relevant styles are in public and the templating engine files are located in views. 所有相关样式都公开,并且模板引擎文件位于视图中。

you can load the static assets by creating the virtual path like 您可以通过创建虚拟路径来加载静态资产,例如
app.use('/assets',express.static(__dirname + '/public/css')); where public is the directory where all your assets are stored,in which css is the folder where is all your css file are stored , you can you the virtual path in the link tag , href attribute for loading the css ,eg: if you have template file ,you write in it ,the link tag <link rel="stylesheet" type="text/css" href="/assets/create.css"> i have tried with the same directory structure like yours and tried to emulate the bug and fixed the css load issue you can refer https://github.com/ardnahcivar/Node.js-Code-/tree/master/11-17-18 the code 其中public是存储所有资产的目录,css是存储所有css文件的文件夹,您可以在link标记中的虚拟路径,href属性用于加载css,例如:模板文件,您可以在其中编写,链接标记<link rel="stylesheet" type="text/css" href="/assets/create.css">我尝试使用与您相同的目录结构并尝试模仿该错误并修复了CSS加载问题,您可以参考https://github.com/ardnahcivar/Node.js-Code-/tree/master/11-17-18

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM