简体   繁体   中英

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

I'm writing a simple blog from scratch to learn 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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