Node.js核心模块 http模块

前言

http、http2模块都是node.js的核心模块,下面分别对这些模块进行分析。

http模块–创建http服务器和客户端

使用http模块只需要在文件中通过require(“http”) 引入即可。http模块是node.js原生的中最为亮眼的模块。传统的HTTP服务器都会由nginx之类的软件来担任,但是node.js不需要。node.js的http模块本身就可以构建服务器,而且性能非常可靠。

1、Node.js服务端
下面创建一个简单的NOde.js服务器。

const http = require("http")
const server = http.createServer(function(req,res){
    
    
    res.writeHead(200,{
    
    
        "content-type":"text/plain"
    })
    res.end("hello,Node.js!")
})

server.listen(3000,function(){
    
    
    console.log("listening port 3000!")
})

运行这段代码,在浏览器打开http://localhost:3000/ 页面中就会显示“Hello Node.js!”文字

http.createServer()方法返回的是http模板封装的一个基于时间的http服务器。同样,http.request是封装的一个http客户端工具,可以用来向http服务器发起请求。上面的req和res分别是http.IncomingMessage和http.ServerResponse的实例。

http.Server的事件主要有:

  • request:最常用的事件,当客户端请求到来时,该事件被触发,提供req和res两个参数,表示请求和响应信息。
  • connection:当TCP连接建立时,该事件被触发,提供一个socket参数,是net.Socket的实例。
  • close:当服务器关闭时,触发事件

http.createServer()方法其实就是添加了一个request事件监听,利用下面的代码同样可以实现效果。

const http = require("http")
const server = new http.Server();


server.on('request', function (req, res) {
    
    
    res.writeHead(200, {
    
    
        "content-type": "text/plain"
    })
    res.end("hello,Node.js!")
})

server.listen(3000, function () {
    
    
    console.log("listening port 3000!")
})

http.IncomingMessage是http请求的信息,提供了以下三个事件:

  • data:当请求体数据到来时该事件被触发。该事件提供一个chunk参数,表示接收的数据。
  • end:当请求体数据传输完毕时该事件被触发,此后不会再有数据。
  • close:用户当前请求结束时,该事件被触发。

http.IncomingMessage提供的属性主要有:

  • method:HTTP请求的方法,如GET
  • headers:HTTP请求头
  • url:请求路径
  • httpVersion:HTTP协议的版本
const http = require("http")

const server = http.createServer(function (req, res) {
    
    
    let data = ""
    req.on('data', function (chunk) {
    
    
        data += chunk;
    })

    req.on("end", function () {
    
    
        let method = req.method;
        let url = req.url;
        let headers = JSON.stringify(req.headers);
        let httpVersion = req.httpVersion;
        res.writeHead(200, {
    
    
            "content-type": "text/html"
        });
        let dataHtml = `<p>data:` + data + `</p>`
        let urlHtml = `<p>url:` + url + `</p>`
        let methodHtml = `<p>method:` + method + `</p>`
        let resdata = dataHtml + urlHtml + methodHtml
        res.end(resdata)
    })
})


server.listen(3000, function () {
    
    
    console.log("listening port 3000!")
})

在这里插入图片描述

http.ServerResponse 是返回给客户端的信息,其常用的方法为:

  • res.writeHead(statusCode,[headers]):向客户端发送响应头。
  • res.write(data,[encoding]):向请求发送内容
  • res.end([data],[encoding]):结束请求

这些方法在上面的代码中已经演示过了,这里就不再演示了。

2、客户端向http服务器发送请求
以上方法都是http模块在服务器端的使用,接下来看客户端的使用。向http服务器发起请求的方法有:

  • http.request(option,[callbakck]):option为json对象,主要字段有host port method path headers 该方法返回一个httpClientRequest实例
  • http.get(option,[callback]) : http.request()使用HTTP请求方式GET的简便方法
const http = require("http")
let reqData = ""
http.request({
    
    
    'host': '127.0.0.1',
    'port': '3000',
    'method': 'get'
}, function (res) {
    
    
    res.on('data', function (chunk) {
    
    
        reqData += chunk;
    })
    res.on('end', function () {
    
    
        console.log(reqData)
    })

})

猜你喜欢

转载自blog.csdn.net/fuhao6363/article/details/129410684