我是node.js的初學者,我在w3schools上學習它。在node.js中加載html樣式表
最近,當我在學習File System時,我來到了fs.readFile方法。作爲第一個參數,我提供了一個鏈接到一個以前創建的html文件。現在該文件附有一個css樣式表,它的href編輯(顯然)。這標誌着我的問題的開始。
經過大量的閱讀在幾個網站上編輯我的代碼噸,這是我的代碼的最終版本。
我的JS,HTML和CSS如下 -
var http = require('http'),
fs = require('fs'),
path = require('path'),
express = require('express'),
app = express();
app.use(express.static(path.join(__dirname, '/public')));
http.createServer(function (req, res) {
fs.readFile('.CSS Transitions - timing function.html', function (err, data) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.end(data);
});
}).listen(8080);
console.log('Server running at =>\n localhost:8080\nCtrl + C to quit');
a
{
\t transition : color 1s, font-size .5s;
\t transition-timing-function : ease;
\t color : black;
\t font-size : 30px;
}
a:hover
{
\t color : red;
\t font-size : 40px;
}
<!DOCTYPE html>
<html>
\t <head>
\t \t <title>Transition</title>
\t \t <link rel='stylesheet' type='text/css' href='css/CSS Transitions - timing function.css'>
\t </head>
\t <body>
\t \t <h2>Links</h2>
\t \t <ul>
\t \t \t <li><a href='http://www.htmldog.com'>HTML-Dog</a></li>
\t \t \t <li><a href='http://www.imdb.com'>IMDb</a></li>
\t \t \t <li><a href='http://www.youtube.com'>YouTube</a></li>
\t \t </ul>
\t </body>
</html>
我的目錄結構是
js file
html file
/public
/css
css file
問題 >>不管我做什麼,我的css文件沒有加載。這是頻繁的錯誤 -
將資源解釋爲樣式表,但使用MIME類型text/html傳輸:「http://localhost:8080/css/CSS%20Transitions%20-%20timing%20function.css」。
不知道該做什麼了。自2天以來我一直在這裏,請幫助!
非常感謝你。它完美的作品。 雖然,我想知道是否可以使用_fs.readFile()_方法來提供靜態文件。 – Samsite
當然,你的想法是正確的。但是你用http模塊創建服務器,你的響應對象沒有sendFile方法。所以你必須使用「var file = fs.readFile()」,然後用res「res.send(file)」發送文件。但是你已經使用了express模塊,它包裝了http模塊,並且在請求和響應對象中暴露了很多方法。在這個時候響應對象有sendFile方法。所以你可以使用res.sendFile()而不是fs.readFile()。 – Vasi