SoFunction
Updated on 2025-03-02

Create a complete example of server and client using http module

This article describes the use of http module to create servers and clients. Share it for your reference, as follows:

The http module in this article provides a method to create servers and clients. The full name of http is the hypertext transmission protocol, which is based on tcp and belongs to the application layer protocol.

1. Create an http server

const http = require('http');
//Create an http serverlet server = ();
// Listen to the port(8888, '0.0.0.0');
//Set the timeout time(2 * 60 * 1000);
//From the server listening('listening', function () {
  ('Supervisor begins');
});
//Triggered when a client request is received('request', function (req, res) {
  //req means the client request object, it is an instance of the class and a readable stream.  //res means the server-side response object, it is an instance of the class and can be written in the stream.  //Request method  ();
  //Request url  ();
  //Request header information  ();
  //The requested http version  ();
  //The socket object of the request object  ();
  ('hello');
});
// Triggered when the connection is established('connection', function (socket) {
  ('Make a connection');
});
// Triggered when the client sends a CONNECT request to the server('connect', function (req, socket, head) {
  ('Client Connect');
});
//Free when the server is closed, call the close() method.('close', function () {
  ('Server Close');
});
// Triggered when an error occurs('error', function (err) {
  (err);
});
// If the connection has not responded for more than the specified time, it will be triggered.//After timeout, the established connection cannot be reused, and a request needs to be issued to re-establish the connection again('timeout', function (socket) {
  ('Connection timed out');
});

The request object req saves the client's detailed information, including url, request parameters, etc. In order to facilitate parsing these parameters, we can use the () method.

const http = require('http');
const url = require('url');
//Create an http serverlet server = ();
// Listen to the port(8888, '0.0.0.0');
//Triggered when a client request is received('request', function (req, res) {
  //Resolve the url and return a url object  //If parameter two is set to true, the query attribute in the url object will generate an object through ()  let params = (, true);
  //Full URL address  ('href', );
  //Host name, including port  ('host', );
  //Host name, not port  ('hostname', );
  //port  ('port', );
  //protocol  ('protocol', );
  //Path, containing query string  ('path', );
  //Path, does not contain query string  ('pathname', );
  //Query string, does not contain ?  ('query', );
  //Query string, including ?  ('search', );
  //Hasked string, including #  ('hash', );
  ('end');
});

Res The response object res can set some parameters that the server responds to the client.

const http = require('http');
const url = require('url');
//Create an http serverlet server = ();
// Listen to the port(8888, '0.0.0.0');
//Triggered when a client request is received('request', function (req, res) {
  //Set response header information  ('Content-Type', 'text/html;charset=utf-8');
  //Get response header information  ('Content-Encoding');
  ('test', 'test');
  //Delete the response header information  ('test');
  //Judge whether the response header has been sent  ( ? 'Sent' : 'Not sent');
  //Note the difference between writeHead() and setHeader(). SetHeader() will not send the response header immediately.  //Which writeHead() will be sent, and the response header set by writeHead() is preferred over setHeader().  (200, {
    'aaa': 'aaa'
  });
  //Judge whether the response header has been sent  ( ? 'Sent' : 'Not sent');
  //How to not send date Date, set to false will not send Date   = false;
  //Set the timeout time of the response  (30 * 1000);
  ('timeout', function () {
    ('Response timeout');
  });
  //Send data to the client  // Since the res response object is also a stream, you can use write() to write data  (('Hello'));
  (('welcome'));
  ('end');
});

2. http client

Sometimes we need to request resources or interfaces of other websites through get or post, and at this time we need to use the http client.

const http = require('http');
const zlib = require('zlib');
let client = ({
  //protocol  'protocol': 'http:',
  //Host name or IP  'hostname': '',
  //port  'port': 80,
  //Request method  'method': 'GET',
  //Request path and query string  'path': '/',
  //Request header object  'headers': {
    'Accept-Encoding': 'gzip, deflate, br'
  },
  //Timeout time  'timeout': 2 * 60 * 1000
});
//Send a request();
//Triggered when the response is received('response', function (res) {
  ('Status:' + );
  ('Response header:' + ());
  //The header information is lowercase  let encoding = ['content-encoding'];
  //Judge whether the content encoding in the response header is overcompressed, and if there is any, decompression is performed.  if ((/\bgzip\b/)) {
    (()).pipe();
  } else if ((/\bdeflate\b/)) {
    (()).pipe();
  } else {
    ();
  }
});
// An error triggered during the request process('error', function (err) {
  (err);
});
//Free when the socket is assigned to the request('socket', function (socket) {
  (2 * 60 * 1000);
  ('timeout', function () {
    // Terminate this request    ()
  });
});

You can also use the () easy method to make get requests.

const http = require('http');
//The () will be called automatically, and the default is get request.('', function (res) {
  ('data', function (data) {
    (());
  });
});

I hope this article will be helpful to everyone's programming.