Node.js完整的響應html頁面(包括css,js檔案)
主要思想就是任何一個靜態檔案也應該做響應,一個獲取靜態檔案都應當請求來處理,這是主要思想。
同時要注意兩點。第一,對於不同的檔案型別,比如html,css,js,請求頭裡面的檔案型別需要根據不同的檔案型別註明,
第二,檔案的路徑需要表達準確,fs.readFile方法的第一個引數path是已起服務的檔案為根目錄,這裡就是以server.js檔案的所在目錄為根目錄
檔案目錄
資料夾public
Index.html
Css資料夾
Reset.css
Index.css
Js資料夾
vue.min.js
Index.js
Server.js
Server.js和資料夾publi同級
來看server.js程式碼
var http = require('http');
var fs = require('fs');
var url = require('url');
// 建立伺服器
http.createServer( function (request, response) {
// 解析請求,包括檔名
var pathname = url.parse(request.url).pathname;
var postfix = pathname.match(/(\.[^.]+|)$/)[0];//取得字尾名
// 輸出請求的檔名
console.log("Request for " + pathname + " received.");
// 從檔案系統中讀取請求的檔案內容
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
// HTTP 狀態碼: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html; charset=utf-8'});
}else{
// HTTP 狀態碼: 200 : OK
// Content Type: text/plain
console.log(postfix);
if(postfix==='html'){
response.writeHead(200, {'Content-Type': 'text/html'});
}else if(postfix==='css'){
response.writeHead(200, {'Content-Type': 'text/css'});
}
else if(postfix==='js'){
response.writeHead(200, {'Content-Type': 'application/javascript'});
}else{
}
// 響應檔案內容
response.write(data.toString());
}
// 傳送響應資料
response.end();
});
}).listen(8080);
// 控制檯會輸出以下資訊
console.log('Server running at http://127.0.0.1:8080/');
最後在命令列輸入node server.js 把伺服器起起來
然後在瀏覽器開啟http://127.0.0.1:8080/public/index.html