1. HTTP server #

HTTP is a hypertext transfer protocol built on TCP and belongs to the application layer protocol.

1.1 Creating an HTTP Server

let server  = http.createServer([requestListener]);
server.on('request',requestListener);
Copy the code
  • RequestListener A process that the server performs when it receives a connection from a client
    • HTTP.IncomingMessage Request object
    • HTTP.ServerResponse Object Server – side response object

1.2 Starting the HTTP Server

server.listen(port,[host],[backlog],[callback]);
server.on('listening',callback);
Copy the code
  • Port Indicates the listening port number
  • Host Specifies the listening address
  • Backlog specifies the number of client connections in the wait queue
let http = require('http');
let server = http.createServer(function(req,res){
}).listen(8080,'127.0.0.1'.function(){console.log('Server listening! ')});
Copy the code

1.3 Shutting down the HTTP Server

server.close();
server.on('close'.function() {});Copy the code
let http = require('http');
let server = http.createServer(function(req,res){
});
server.on('close'.function(){
    console.log('Server down');
});
server.listen(8080,'127.0.0.1'.function(){
    console.log('Server listening! ')
    server.close();
});
Copy the code

1.4 Listening server error

server.on('error'.function() {if(e.code == 'EADDRINUSE'){
         console.log('The port number is in use! ; }});Copy the code

1.5 the connection

let server = http.createServer(function(req,res){
});
server.on('connection'.function(){console.log(the client connection has been established); });Copy the code

1.6 setTimeout

If the timeout period is set, existing connections cannot be reused and requests must be sent to re-establish connections. The default timeout period is 2 minutes

server.setTimeout(msecs,callback);
server.on('timeout'.function(){
    console.log('Connection timed out');
});
Copy the code

1.7 Obtaining Client Request Information

  • request
    • Method Request method
    • Url Request path
    • Headers Request header object
    • HttpVersion HTTP version of the client
    • Socket The socket object that listens to client requests
      let http = require('http');
      let fs = require('fs');
      let server = http.createServer(function(req,res){
      if(req.url ! ='/favicon.ico') {let out = fs.createWriteStream(path.join(__dirname,'request.log'));
      out.write('method='+req.method);
      out.write('url='+req.url);
      out.write('headers='+JSON.stringify(req.headers));
      out.write('httpVersion='+req.httpVersion);
      }
      }).listen(8080,'127.0.0.1);
      Copy the code
let http = require('http');
let fs = require('fs');
let server = http.createServer(function(req,res){
  let body = [];
  req.on('data'.function(data){
    body.push(data);
  });
  req.on('end'.function() {let result = Buffer.concat(body);
      console.log(result.toString());
  });
}).listen(8080,'127.0.0.1);
Copy the code

1.8 the querystring

The querystring module is used to convert the URL string to the querystring in the URL

The 1.8.1 parse method is used to convert strings into objects

querystring.parse(str,[sep],[eq],[options]);
Copy the code

The 1.8.2 stringify method is used to convert an object to a string

querystring.stringify(obj,[sep],[eq]);
Copy the code

1.9 the querystring

url.parse(urlStr,[parseQueryString]);
Copy the code
  • Href The original URL string converted
  • Protocol used by the protocal client to send requests
  • Slashes whether the // separator is used between the protocol and the path
  • Host URL The complete address and port number in the string
  • Auth The authentication part of the URL string
  • Hostname URL Specifies the full address in the string
  • Port Indicates the port number in the URL string
  • Pathname Specifies the path of the URL string, excluding the query string
  • Search query string containing?
  • Path Path, which contains the query string
  • Query A query string that does not contain a start string?
  • Hash Hash character string containing#

1.10 Sending the Server Response Flow

The HTTP. ServerResponse object represents the response object

1.10.1 writeHead

response.writeHead(statusCode,[reasonPhrase],[headers]);
Copy the code
  • Content-type Indicates the content type
  • Location redirects the client to another URL
  • Content-disposition specifies a file name to download
  • Content-length Specifies the bytes of the server response
  • Set-cookie Creates a cookie on the client
  • Content-encoding Specifies the encoding of the server response content
  • Cache -cache Enables the cache mechanism
  • Expires is used to set a cache expiration time
  • Etag specifies that the data is not reloaded when the server responds that the content has not changed

1.10.2 Header

Set, get, and delete the Header

response.setHeader('Content-Type'.'text/html; charset=utf-8');
response.getHeader('Content-Type');
response.removeHeader('Content-Type'); Response. headersSent Checks whether the response header has been sentCopy the code

1.10.3 headersSent

Determines whether the response header has been sent

let http = require('http');
let server = http.createServer(function(req,res){
  console.log(resopnse.headersSent?"Response header has been sent":"Response header not sent!");
  res.writeHead(200,'ok); console.log(resopnse.headersSent?" Response header sent ":" Response header not sent!" ); });Copy the code

1.10.4 sendDate

Don’t send the Date

res.sendDate = false;
Copy the code

1.10.5 write

You can use the write method to send the response content

response.write(chunk,[encoding]);
response.end([chunk],[encoding]);
Copy the code

1.10.6 timeout

You can use the setTimeout method to set a timeout for a response, and if you do not respond within the specified time, the timeout event is emitted

response.setTimeout(msecs,[callback]);
response.on('timeout',callback);
Copy the code

1.10.7 close

Before the end method of the response object is called, the close event of the HTTP. ServerResponse object is emitted if the connection is broken

response.on('close',callback);
Copy the code

1.10.8 parser

.net onconnection _http_server. Js connect to monitor connectionListenerInternal socketOnData onParserExecuteCommon parserOnIncomingCopy the code

2. HTTP client

2.1 Request data from other websites

let req = http.request(options,callback);
req.on('request',callback);
request.write(chunk,[encoding]);
request.end([chunk],[encoding]);

Copy the code
  • Host Specifies the destination domain name or host name
  • Hostname Specifies the destination domain name or hostname. If both hostname and host are specified, hostname is preferred
  • Port Specifies the port number of the target server
  • LocalAddress Indicates the local interface
  • SocketPath Specifies the Unix domain port
  • Method Specifies the HTTP request mode
  • Path Specifies the request path and query string
  • Headers specifies the client request header object
  • Auth specifies the authentication part
  • Agent is used to specify the HTTP proxy. In Node.js, the http. agent class represents an HTTP proxy. By default, keep-alive connections are used, and HTTP
let http = require('http');
let options = {
    hostname: 'localhost',
    port: 8080,
    path: '/',
    method: 'GET'
}
let req = http.request(options, function (res) {
    console.log('Status :' + res.statusCode);
    console.log('Response header :' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data'.function (chunk) {
        console.log('Response content', chunk);
    });
});
req.end();
Copy the code

2.2 Canceling a Request

You can use the abort method to terminate the request

req.abort();
Copy the code

2.3 Listening for Error Events

An error event is raised if something goes wrong during the request

request.on('error'.function(err){});
Copy the code

2.4 the socket

Description A socket event was triggered when a port was allocated to the connection during connection establishment

req.on('socket'.function(socket){
  socket.setTimeout(1000);
  socket.on('timeout'.function(){req.abort()});
});
Copy the code

2.5 the get

You can use the GET method to send data to the server

http.get(options,callback);
Copy the code

2.6 addTrailers

You can use the addTrailers method of the Response object to append a header to the end of the server response

let http = require('http');
let path = require('path');
let crypto = require('crypto');


let server = http.createServer(function (req, res) {
    res.writeHead(200, {
        'Transfer-Encoding': 'chunked'.'Trailer': 'Content-MD5'
    });
    let rs = require('fs').createReadStream(path.join(__dirname, 'msg.txt'), {
        highWaterMark: 2
    });
    let md5 = crypto.createHash('md5');
    rs.on('data'.function (data) {
        console.log(data);
        res.write(data);
        md5.update(data);
    });
    rs.on('end'.function () {
        res.addTrailers({
            'Content-MD5': md5.digest('hex')}); res.end(); }); }).listen(8080);Copy the code
let http = require('http');
let options = {
    hostname: 'localhost',
    port: 8080,
    path: '/',
    method: 'GET'
}
let req = http.request(options, function (res) {
    console.log('Status :' + res.statusCode);
    console.log('Response header :' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data'.function (chunk) {
        console.log('Response content', chunk);
    });
    res.on('end'.function () {
        console.log('trailer', res.trailers);
    });
});
req.end();
Copy the code

2.7 Creating a Proxy Server

let http = require('http');
let url = require('url');
let server = http.createServer(function (request, response) {
    let {
        path
    } = url.parse(request.url);
    let options = {
        host: 'localhost',
        port: 9090,
        path: path,
        headers: request.headers
    }
    let req = http.get(options, function (res) {
        console.log(res);
        response.writeHead(res.statusCode, res.headers);
        res.pipe(response);
    });
    req.on('error'.function (err) {
        console.log(err);
    });
    request.pipe(req);
}).listen(8080);Copy the code