一、程式碼結構
//1.引入相關模組
var http=require("http")
var url=require("url")
var fs=require("fs")
//2.建立服務以及處理請求和響應
var server=http.createServer(function(req,res){
//處理請求與響應部分
}
//3.監聽某一個埠
server1.listen(81,function(){
console.log("servers is success,listening on 81port!")
})
複製程式碼
二、http.createServer
var server=http.createServer(function(req,res){
var pathname=url.parse(req.url).pathname
if(pathname==="/index.html"){
var conFile=fs.readFileSync("."+pathname,"utf-8")
// res.writeHead(200,{'content-type':'text/html;charset=utf-8;'})
res.statusCode = 200
res.setHeader('Content-Type', 'text/html;charset=utf-8')
res.end(conFile)
}
複製程式碼
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div{color: red;}
</style>
</head>
<body>
<div>index.html</div>
</body>
</html>
複製程式碼