nodejs創建服務並加載一個html文件


var http=require("http");
//導入文件模塊
var fs=require("fs");
var server =http.createServer(function(req,res){

//控制台打印信息
console.log("server is working");


//結束服務器響應,注:沒有res.end(),打開網頁時,頁面將處於一直加載的狀態
// res.end("server end.");

//設置頭信息
res.setHeader("Content-Type","text/html;charset='utf-8'");

//直接在頁面中打印出來的內容
//res.write("response write content.");

//讀文件
fs.readFile("./index.html","utf-8",function(err,data){
if(err) {
console.log("index.html loading is failed :"+err);
}
else{
//返回index.html頁面
res.end(data);
}

});

//監聽端口,注:一個程序只能監聽一個端口
}).listen(8888);

index.html:

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>

你好,歡迎來到nodejs的世界,這里是我的首頁。
</body>
</html>




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM