nodejs搭建web服务器

时间:2022-02-17 10:18:24

一、代码结构

//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>