2017-07-04 52 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 
相关问题