2017-07-04 51 views
0

我是NodeJS的新手,我使用Express來爲我的帕格文件/視圖服務。此外,我使用「express-sass-middleware」來編譯和提供scss/css文件。一切運作良好,但不幸的是,CSS不適用。使用Express和SASS的Node.JS - 未應用編譯的CSS文件

我app.js文件看起來像:

var express = require('express'); 
var sassMiddleware = require('express-sass-middleware'); 
var app = express(); 
app.set('view engine', 'pug'); 

app.get('/css/bootstrap.css', sassMiddleware({ 
    file: 'css/bootstrap.scss', // the location of the entry point, 
            // this can also be a directory 

    precompile: true,     // should it be compiled on server start 
            // or deferred to the first request 
            // - defaults to false 
})); 

app.get('/', function (req, res) { 
    res.render('index', { 
     varTitle: 'Hello World' 
    }); 
}); 

app.listen(3000, function() { 
    console.log('Example app listening on port 3000!'); 
}); 

而且我簡單的CSS文件的樣子:

// $icon-font-path: /3rdparty/fonts; 

// @import 'bootstrap/bootstrap'; 
// @import './node_modules/bootstrap-sass/assets/stylesheets/bootstrap/variables'; 

body 
{ 
    background-color: green; 
    font-size: 100px; 
} 

我index.pug文件是:

doctype html 
html(lang='en') 
    head 
    title= varTitle 
    link(ref='stylesheet' type='text/css' href='/css/bootstrap.css') 
    body 
    h1= varTitle 

現在,當我使用「node app.js」啓動我的網絡服務器時,訪問http://localhost:3000,我看到「Hello World」,但不幸的是身體背景不是綠色的,文字也不是100px。這意味着該css文件不適用。但是當我訪問http://localhost:3000/css/bootstrap.css時,我看到了有效的css文件。

任何人都知道我在這裏失蹤?我有點困惑,我直接訪問它時看到CSS源代碼,但瀏覽器不適用CSS樣式。我已經嘗試了不同的瀏覽器沒有任何成功。他們都沒有申請的CSS文件。

回答

0

你有index.pug文件加載css文件打字錯誤。你提到了ref,而它應該是rel

link(rel='stylesheet' type='text/css' href='/css/bootstrap.css') 

高興地幫助你。

+0

是的,這解決了錯誤。謝謝! – Nrgyzer

0

您似乎沒有從您的nodejs服務器代碼提供靜態文件。你必須添加你的CSS DIR爲了讓您的HTML代碼的訪問:現在

app.use('/static', express.static('public')) 

,你可以加載在從/靜態路徑前綴的公共目錄中的文件。

http://localhost:3000/static/images/kitten.jpg 
http://localhost:3000/static/css/style.css 
http://localhost:3000/static/js/app.js 
http://localhost:3000/static/images/bg.png 
http://localhost:3000/static/hello.html 
相關問題