nodejs搭建web服务器

一、代码结构

//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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容