http://www.phpstudy.net/c.php/18720.html
node不利用框架怎么實現對靜態HTML、css、js的服務? 初學nodeJS,在使用nodejs構建靜態文件服務器的時候,遇到下面問題。 用戶請求index.html時,我使用fs.readFile讀取index.html並將data返回,代碼如下: function serverStatic(req,res){ var filePath; if(req.url==="/"){ filePath = "index.html"; } else{ filePath = "./" + url.parse(req.url).pathname; } fs.exists(filePath,function(err){ if(err){ send404(res); }else{ fs.readFile(filePath,function(err,data){ if(err){ res.end("<h1>500</h1>服務器內部錯誤!"); }else{ res.writeHead(200,{'content-type':'text/html'}); res.end(data.toString()); } });//fs.readfile } })//path.exists }//serverStatic 那么問題來了,如果我的HTML頁面引用了外部的css或者js,那么這些外部文件不會被加載··· 這個問題怎么解決? 嘗試: index源碼: <!doctype html> <html> <head> <meta charset='utf-8'> <link href="css/index.css"> </head> <body> <a href="flexbox.html">看看伸縮盒?</a> </body> </html> css: body{background-color:red;} app.js: var http=require('http'); var fs=require('fs'); var url=require('url'); var path=require('path'); var PORT=9090; //添加MIME類型 var MIME_TYPE = { "css": "text/css", "gif": "image/gif", "html": "text/html", "ico": "image/x-icon", "jpeg": "image/jpeg", "jpg": "image/jpeg", "js": "text/javascript", "json": "application/json", "pdf": "application/pdf", "png": "image/png", "svg": "image/svg+xml", "swf": "application/x-shockwave-flash", "tiff": "image/tiff", "txt": "text/plain", "wav": "audio/x-wav", "wma": "audio/x-ms-wma", "wmv": "video/x-ms-wmv", "xml": "text/xml" }; var server = http.createServer(serverStatic); function serverStatic(req,res){ var filePath; if(req.url==="/"){ filePath = "index.html"; } else{ filePath = "./" + url.parse(req.url).pathname; } fs.exists(filePath,function(err){ if(!err){ send404(res); }else{ var ext = path.extname(filePath); ext = ext?ext.slice(1) : 'unknown'; var contentType = MIME_TYPE[ext] || "text/plain"; fs.readFile(filePath,function(err,data){ if(err){ res.end("<h1>500</h1>服務器內部錯誤!"); }else{ res.writeHead(200,{'content-type':contentType}); res.end(data.toString()); } });//fs.readfile } })//path.exists } server.listen(PORT); console.log("Server runing at port: " + PORT + "."); function send404(res){ res.end("<h1>404</h1><p>file not found</p>") } chrome查看網絡: 我的文件結構 那么問題來了,你的為請求的每個資源寫讀取文件處理 前幾天剛有人問這個問題的 http://.com/q/1010000004317668?_ea=567469 利用nodejs搭建靜態文件服務器 下面是一個靜態文件訪問的模塊 /** * 引入模塊 * @type {[type]} */ var fs =require("fs"); var mime =require("mime"); var path =require("path"); /*******************************************************************************************/ /** * [Send 創建發送響應對象] */ function Send(){}; Send.prototype.cache={};//設置緩存變量,因為緩存變量比讀取文件要快 /** * 錯誤404頁面 * @param {[type]} res [description] * @return {[type]} [description] */ Send.prototype.err404 = function(res){ res.writeHead(404,{"Content-Type":"text/plain"}); res.write("404 Not Fount !"); res.end(); }; /** * 正確訪問頁面 * @param {[type]} res [description] * @param {[type]} fileName [description] * @param {[type]} fileContent [description] * @return {[type]} [description] */ Send.prototype.sendFile = function(res,fileName,fileContent){ res.writeHead(200,{"Content-Type":mime.lookup(path.basename(fileName))}); res.end(fileContent); }; /** * 發送靜態頁面方法 * @param {[type]} res [description] * @param {[type]} absPath [description] * @return {[type]} [description] */ Send.prototype.serveStatic = function(res,absPath){ var _this=this; if(this.cache[absPath]){ this.sendFile(res,absPath,this.cache[absPath]); }else{ fs.exists(absPath,function(exists){ if(exists){ fs.readFile(absPath,function(err,data){ if(err){ _this.err404(res); }else{ _this.sendFile(res,absPath,data); } }) }else{ _this.err404(res); } }) } }; Send.prototype.staticDirectory=function(req,url){ var filePath=false; if(new RegExp("^/"+url+"/.*").test(req.url)){ filePath=url+req.url; } var absPath="./"+filePath; return absPath; } /*******************************************************************************************/ module.exports=Send; 調用方法 /** * 引入HTTP組建,創建HTTP服務器的核心組件 * @type {[type]} */ var http=require("http"); var sio=require("socket.io"); /** * 引入自定義組件, * @type {[type]} */ var staticService=require("./modules/staticService"); /*************************************************/ /** * 創建http服務 * @param {[type]} req [description] * @param {[type]} res){ var filePath [description] * @return {[type]} [description] */ var server = http.createServer(function(req,res){ var send=new staticService(); var absPath=send.staticDirectory(req,"public") send.serveStatic(res,absPath); }); server.listen(8200,function(){ console.log("Http server create success on : localhost:8200"); }) fs.exists(filePath,function(err) 如果文件存在,回掉函數的第1個參數為true var http=require('http'); var fs=require('fs'); var url=require('url'); var path=require('path'); var PORT=9090; //添加MIME類型 var MIME_TYPE = { "css": "text/css", "gif": "image/gif", "html": "text/html", "ico": "image/x-icon", "jpeg": "image/jpeg", "jpg": "image/jpeg", "js": "text/javascript", "json": "application/json", "pdf": "application/pdf", "png": "image/png", "svg": "image/svg+xml", "swf": "application/x-shockwave-flash", "tiff": "image/tiff", "txt": "text/plain", "wav": "audio/x-wav", "wma": "audio/x-ms-wma", "wmv": "video/x-ms-wmv", "xml": "text/xml" }; var server = http.createServer(serverStatic); function serverStatic(req,res){ var filePath; if(req.url==="/"){ filePath = "CSSTest.html"; } else{ filePath = "./" + url.parse(req.url).pathname; } fs.exists(filePath,function(err){ if(!err){ send404(res); }else{ var ext = path.extname(filePath); ext = ext?ext.slice(1) : 'unknown'; var contentType = MIME_TYPE[ext] || "text/plain"; fs.readFile(filePath,function(err,data){ if(err){ res.end("<h1>500</h1>服務器內部錯誤!"); }else{ res.writeHead(200,{'content-type':contentType}); res.end(data.toString()); } });//fs.readfile } })//path.exists } server.listen(PORT); console.log("Server runing at port: " + PORT + "."); 問題已解決,link css的時候,不能忘了 rel="stylesheet"