Learn about the Node HTTP module

This article documents a simple use and understanding of the HTTP module.

  • The HTTP server
  • The HTTP client
  • conclusion

1. HTTP server

So let’s do a little example

Server:

let http = require('http')
let server = http.createServer((req, res) = > {
  let buf = []
  req.on('data', data => {
    buf.push(data)
  })
  req.on('end', () = > {let str = Buffer.concat(buf).toString()
    res.end(str)
  })
})

server.listen(8080, () = > {console.log('server start')})Copy the code

General code execution flow:
Http.createserver () returns the newly created http.server instance. Http. Server inherits from net.Server. RequestListener is a function that is automatically added to the ‘request’ event.


The ‘request’ event is emitted each time a request is made. HTTP services are provided on a request basis.

The http.IncomingMessage object, which can be used to access the request method, message header, and data of the request (in the figure, request header and data are separated).

ServerResponse object, the server through HTTP.ServerResponse instance, to the client (data requester) to return this data. Including the response header, response body (internal socket to send information).

HTTP server: On the SOCKET of the TCP module, the received data is parsed into the request header and packet body, and the returned response header and packet body are assembled into data and sent out.

1.1 the request:

The request message consists of the following components

  • Header: Request method, request URI, protocol version, and optional request header fields
  • A blank line
  • Message body: The content entity constitutes the data.

The Node HTTP module parses the data into (blank line split, header and message format) :

Req.method req.httpVersionMajor req.httpVersionMinor req.httpVersion req.upgrade... req.headers = { Content-Length:15Content-Type: application/x-www-form-urlencoded ... . }// Packet body: a req readable stream object that continues to read the packet body dataCopy the code

1.2 the response

The server returns the request data to the client (the data requester) via the HTTP. ServerResponse instance. Including the response header, response body (internal socket to send information).

In the write operation of TCP connection, the Node HTTP module splices data write cache (with blank line splicing, packet header and message format) into:
HTTP/1.1 200 OK Date: Sat, 30 Nov 2019 05:10:05 GMT Connection: close Content-Length: 25Copy the code

Method of passage

// Specific usage reference document

// Set the header, the header is not sent
response.setHeader(name, value)
This method can only be called once on the message and must be called before response.end() is called.
response.writeHead()
// If this method is called and Response.writehead () has not been called, it switches to implicit response header mode and flushes the implicit response header.
// This will send a response body. This method can be called multiple times to provide contiguous fragments of the response body.
response.write()
// This method signals to the server that all response headers and bodies have been sent and that the server should consider the message complete. This response.end() method must be called on each response.
response.end() Copy the code

2. HTTP client

The client makes a request to the HTTP server:
let http = require('http')
let options = {
  host: 'localhost'.port: 8080.method: 'POST'.headers: {
    'content-type': 'application/x-www-form-urlencoded'}}// The request does not issue that req is a writable stream
let req = http.request(options)

req.on('response', res => {
  console.log(res.headers)
  let buf = []
  res.on('data', data => {
    buf.push(data)
  })
  res.on('end', () = > {console.log(Buffer.concat(buf).toString())
  })
})
// write Writes data to the request body
req.write('name=luoxiaobu&title=http')
// The actual request header will be sent with the first block of data, or when request.end() is called.
req.end()Copy the code

General code execution flow:

Http.request () returns an instance of the http.ClientRequest class. HTTP.ClientRequest creates a socket internally to initiate a request.

ClientRequest instances can be considered writable streams. If a file needs to be uploaded using a POST request, it is written to the ClientRequest object.

Response Event Is emitted each time a data response is returned from the server.

The http.IncomingMessage object, which can be used to access the response status, headers, and data returned by the server.

HTTP client: On the SOCKET of the TCP module, the client assembs the request header and the packet body into data and sends it out. The received data is parsed out into the response header and packet body.

2.1 the request:

In the write operation of TCP connection, the Node HTTP module concatenates data cache (with blank line concatenation, packet header and message format) into:
// A blank line in the middle "POST/HTTP/1.1 Content-type: application/x-www-form-urlencoded Host: localhost:8080 Connection: Close Transfer-encoding: chunked "+ Part or all of the request body dataCopy the code

Method of passage

// Specific usage reference document
const postData = querystring.stringify({
  'msg': Hello world
});

const options = {
  hostname: 'localhost:8080'.path: '/upload'.method: 'POST'.headers: {
    'Content-Type': 'application/x-www-form-urlencoded'.'Content-Length': Buffer.byteLength(postData)
  }
};
// The header is resolved internally
const req = http.request(options, (res) => {
 
});

// This will send a response body. This method can be called multiple times to provide contiguous fragments of the response body.
response.write()
// This method signals to the server that all response headers and bodies have been sent and that the server should consider the message complete. This response.end() method must be called on each response.
response.end() Copy the code

2.2 the response

Response message graph:

The response packet consists of the following components

  • Header: protocol version, status code (numeric code indicating success or failure of the request), reason phrase used to explain the status code, optional response header field
  • A blank line
  • Packet body: indicates the entity body.

The Node HTTP module parses the data into:

Header: res.statusCode = statusCode; res.statusMessage = statusMessage; res.httpVersionMajor res.httpVersionMinor res.httpVersion res.upgrade ... res.headers = { Content-Length:15Content-Type: application/x-www-form-urlencoded ... . }// Body part: a readable stream object that continues to read the body data of the messageCopy the code

3. Summary

This article records the simple use and understanding of HTTP module, to understand HTTP module, also need to read more documents, code practice.

The examples in this paper are rough and inaccurate.


Resources: << illustrated HTTP>>

Nodejs.org/dist/latest…