node不利用框架怎么實現(xiàn)對靜態(tài)HTML,css,js的服務
1 回答

慕萊塢森
TA貢獻1810條經(jīng)驗 獲得超4個贊
用戶請求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
添加回答
舉報
0/150
提交
取消