簡體   English   中英

node.js不會在所有頁面中加載CSS樣式

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

我正在從頭開始編寫一個簡單的博客,以學習node.js + express。 不過,當我嘗試訪問嵌套的目錄時,我很困惑,無法加載樣式。 例如:

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

將不使用樣式,而僅使用“ / posts”將。

知道是什么原因造成的嗎? 這是完整的代碼:

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)

這是目錄結構:

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

所有相關樣式都公開,並且模板引擎文件位於視圖中。

您可以通過創建虛擬路徑來加載靜態資產,例如
app.use('/assets',express.static(__dirname + '/public/css')); 其中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