nodejs静态伺服

1.引入required模块,使用require指令来获取node.js中的模块
2.创建服务器,服务器可以监听客户端发送的请求
3.接收请求和响应请求,客户端可以通过浏览器或终端发送http请求,服务器接收请求后返回响应数据。

//http协议模块
const http = require("http");
//文件系统模块
const fs = require("fs");

//创建服务,返回一个服务对象,监听对象动态
const server = http.createServer();
//监听request事件,只有客户端有请求,就会被监听到
server.on("request",(request,response)=>{
	//常用方法
      console.log(request)	// request 接收前台请求的对象
      console.log(response)	// response 返回给前台数据的对象
	  console.log(request.url) //request.url 请求的地址
      console.log(request.method)//request.method 请求的方式
      console.log(request.httpVersion)//request.httpVersion 当前http请求的版本号
      console.log(request.socket.localPort) //查询ip地址
      console.log(request.socket.localAddress) // 端口号查询
      
    //当请求的地址是index.html页面,且请求方式为get时
    if((req.url == "/" || req.url == "/index.html") && req.method == "GET"){
        fs.readFile("./index.html","utf8",(err,data)=>{//读取index.html
            //err 错误信息
            //data获得的是文件内容的buffer(二进制)数据,想获得原字符串内容要加toString()方法
            if(err){//读取失败时
                console.log('找不到该页面')
            }
            //设置响应头信息 有两种方式
            //1. request.setHeader()
            request.setHeader("Content-type","text/html")
            //2. request.writeHead()
            //request.writeHead(200,{'Content-type':'text/html'})   //200是http状态码
            //注意:setHeader()并不会立即发送响应头,而writeHead()会发送,
            //writeHead()设置的响应头比setHeader()的优先。
            
            request.end(data);//传输给前台页面数据 本次响应结束
        })
    }
     response.write("hello world") //返回信息到前端,不常用,可以写多个,但在响应结束前前不会显示
    // response.write("hello world")
    // response.write("hello world")

    response.end("end")//传输数据 返回信息给前台,结束本次响应

    
})

server.listen(3000,()=>{//监听3000端口
    console.log("服务器启动成功")
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值