Node.js core module http module

foreword

The http and http2 modules are the core modules of node.js, and these modules are analyzed separately below.

http module – create http servers and clients

To use the http module, you only need to import it through require("http") in the file. The http module is the most eye-catching module in the native node.js. The traditional HTTP server will be served by software such as nginx, but node.js does not need it. The http module of node.js can build the server itself, and the performance is very reliable.

1. Node.js server
Create a simple Node.js server below.

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!")
})

Run this code, and the text "Hello Node.js!" will be displayed in the browser when you open http://localhost:3000/

The http.createServer() method returns a time-based http server encapsulated by the http template. Similarly, http.request is an encapsulated http client tool that can be used to initiate a request to the http server. The req and res above are instances of http.IncomingMessage and http.ServerResponse respectively.

The events of http.Server mainly include:

  • request: The most commonly used event, which is triggered when a client request arrives, and provides two parameters, req and res, indicating request and response information.
  • connection: When the TCP connection is established, this event is triggered, and a socket parameter is provided, which is an instance of net.Socket.
  • close: triggers an event when the server is closed

The http.createServer() method is actually adding a request event listener, and the effect can also be achieved by using the following code.

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 is the information requested by http, and provides the following three events:

  • data: This event is triggered when the request body data arrives. The event provides a chunk parameter, which represents the received data.
  • end: This event is triggered when the request body data is transmitted, and there will be no more data after that.
  • close: This event is triggered when the user's current request ends.

The properties provided by http.IncomingMessage mainly include:

  • method: HTTP request method, such as GET
  • headers: HTTP request header
  • url: request path
  • httpVersion: HTTP protocol version
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!")
})

insert image description here

http.ServerResponse is the information returned to the client, and its commonly used methods are:

  • res.writeHead(statusCode,[headers]): Send the response header to the client.
  • res.write(data,[encoding]): Send content to the request
  • res.end([data],[encoding]): end request

These methods have been demonstrated in the above code, and will not be demonstrated here.

2. The client sends a request to the http server.
The above methods are the use of the http module on the server side. Next, look at the use of the client. The methods of initiating a request to the http server are:

  • http.request(option,[callbakck]): option is a json object, the main fields are host port method path headers This method returns an instance of httpClientRequest
  • http.get(option,[callback]) : http.request() is a convenient way to use the HTTP request method 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)
    })

})

Guess you like

Origin blog.csdn.net/fuhao6363/article/details/129410684