In this article, we will learn about Node’s built-in HTTP module, which is mainly used to build HTTP server and client

1. HTTP server

(1) Create a service

The HTTP Server is implemented through http.Server. We can create an HTTP. Server in the following two ways

const http = require('http')
/ / method
var server = new http.Server()
/ / method 2
var server = http.createServer()
Copy the code

(2) Bind events

HTTP.Server is an event-based Server. We need to specify the corresponding handlers for different events to complete the function

The most common event is request, which is triggered when the server receives a request

The event handler receives two parameters, corresponding to http.IncomingMessage and http.ServerResponse

server.on('request'.function(message, response) {
    console.log(message instanceof http.IncomingMessage) // true
    console.log(response instanceof http.ServerResponse) // true
    console.log('Request received')})Copy the code

(3) Attribute method

Http. Server also has some common properties and methods, which are described below:

  • listen(): Listening connection
  • close(): Close the connection
  • setTimeout(): Sets the timeout period
  • listening: Whether the connection is being listened on
  • maxHeadersCount: Maximum number of incoming headers. The default value is2000
  • timeout: Waiting time of the socket before timeout. The default value is0 ms
  • headersTimeout: The time to wait before receiving the complete header. The default is60000 ms
  • keepAliveTimeout: The time to wait after the last response is written and before the socket is destroyed. The default is5000 ms
server.listen(8888.'127.0.0.1'.function() {
    console.log('server running at http://127.0.0.1:8888)})Copy the code

(4) http.IncomingMessage and http.ServerResponse

HTTP.IncomingMessage represents the received data object. The commonly used properties and methods are as follows:

Properties and methods describe
aborted Whether the request has been terminated
complete Whether the complete message was received and successfully parsed
rawHeaders List of original request headers
headers Request header object
url The URL string
httpVersion The HTTP version
method Request method
statusCode The status code
statusMessage State information

Http. ServerResponse indicates the response object to be sent. The commonly used properties and methods are as follows:

Properties and methods describe
hasHeader(name) Whether there is a specific response header
getHeader(name) Gets the specified response header
getHeaders() Gets all response headers
getHeaderNames() Gets the names of all response headers
setHeader(name, value) Setting the response header
removeHeader(name) Delete the response header
setTimeout(msecs[, callback]) Setting timeout
writeHead(statusCode[, statusMessage][, headers]) Send response header
write(chunk[, encoding][, callback]) Sending response body
end([data[, encoding]][, callback]) All data has been sent
headersSent Whether the response header has been sent
statusCode Status code, which defaults to 200
statusMessage Status information, standard information that defaults to status codes

(5) A complete example

// server.js
const http = require('http')
const path = require('path')
const fs = require('fs')
const server = http.createServer()
server.on('request'.function(message, response) {
    let url = message.url
    if (url === '/') url = '/index.html'
    fs.readFile(path.join(__dirname, url), function(error, data) {
        if (error) {
            response.writeHead(404, {'Content-Type': 'plain/html'})}else {
            response.writeHead(200, {'Content-Type': 'text/html'})
            response.write(data)
        }
        response.end()
    })
})
server.listen(8888.'127.0.0.1'.function() {
    console.log('server running at http://127.0.0.1:8888)})Copy the code
<! DOCTYPEhtml>
<html>
<head>
    <meta charset="UTF-8">
    <title>Index</title>
</head>
<body>
    <p>Index Page</p>
</body>
</html>
Copy the code
<! DOCTYPEhtml>
<html>
<head>
    <meta charset="UTF-8">
    <title>About</title>
</head>
<body>
    <p>About Page</p>
</body>
</html>
Copy the code

2. HTTP client

(1) Create a service

The HTTP client is used to send HTTP requests. It is implemented based on http.request and creates the signature of the method as follows:

http.request(options[, callback])
http.request(url[, options][, callback])
Copy the code
  • Url: Request address. The type is string or URL

  • Options: request parameters. The type is object. Common attributes are as follows:

    • Headers : request head
    • MaxHeaderSize <number> : specifies the maximum length of the request header. The default value is8192 Bytes
    • Method <string> : request method. The default value isGET
    • Protocol <string> : network protocol. The default value ishttp:
    • Host <string> : indicates the requested domain name or IP address. The default value islocalhost
    • Hostname

      : alias of host, and hostname has a higher priority than host
    • Port <number> : request port, default if setdefaultPort, it isdefaultPort, or for80
    • Path <string> : request path. The default value is/
    • Timeout

      : indicates the timeout period
  • Callback: callback function

const http = require('http')
let url = 'http://127.0.0.1:8888/index.html'
let request = http.request(url)
Copy the code

The http.request method returns an http.ClientRequest object

(2) Bind events

The http.ClientRequest object is also event-based. Common events are as follows:

  • If the request is sent successfully, the following events are emitted in sequence:socket -> response(data -> end) -> close
  • If the request fails to be sent, the following events are emitted in sequence:socket -> error -> close
request.on('response'.function(message) {
    console.log(message instanceof http.IncomingMessage) // true
    console.log('Response received')
})
request.on('error'.function(error) {
    console.log(error instanceof Error) // true
    console.log('Error occurred')})Copy the code

(3) Attribute method

The common properties and methods of the http.ClientRequest object are as follows:

  • abort(): indicates that the request was terminated
  • getHeader(name): Gets the request header
  • setHeader(name, value): Sets the request header
  • removeHeader(name): Deletes the request header
  • setTimeout(timeout[, callback]): Sets the timeout period
  • write(chunk[, encoding][, callback]): Sends the request body
  • end([data[, encoding]][, callback]): All data has been sent
// Send data
const querystring = require('querystring')
request.write(querystring.stringify({
    username: 'wsmrzx'.password: '123456'
}))
// Send the end flag
request.end()
Copy the code

(4) A complete example

const http = require('http')
let url = 'http://127.0.0.1:8888/index.html'
let request = http.request(url)
request.on('response'.function(message) {
    let html = ' '
    message.on('data'.function(chunk) {
        html += chunk
    })
    message.on('end'.function() {
        console.log(html)
    })
})
request.on('error'.function(error) {
    console.log(error.message)
})
request.end()
Copy the code