SoFunction
Updated on 2025-03-10

Example of http and https request encapsulation operation implemented by nodejs

This article describes the http and https request encapsulation operations implemented by nodejs. Share it for your reference, as follows:

libs/

const URL = require('url');
const zlib = require('zlib');
const http = require('http');
const https = require('https');
const qs = require('querystring');
function Request(cookie) {
  = [];
 if (cookie !== undefined) {
 (cookie);
 }
}
 = function(host, postData) {
 let headers = {
 'Host': host,
 'Pragma': 'no-cache',
 'Connection': 'keep-alive',
 'Cache-Control': 'no-cache',
 'Content-Type': 'application/x-www-form-urlencoded',
 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4,es;q=0.2',
 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1',
 };
 if () {
  = ('; ');
 }
 if (postData != '') {
 headers['Content-Length'] = (postData);
 }
 return headers;
}
 = function(cookie) {
 let cookies = (';');
 for (let c of cookies) {
 c = (/^\s/, '');
 (c);
 }
 return this;
}
 = function(method, url, params) {
 let postData = (params || {});
 let urlObj = (url);
 let protocol = ;
 let options = {
 hostname: ,
 port: ,
 path: ,
 method: method,
 headers: (, postData),
 };
 return new Promise((resolve, reject) => {
 let req = (protocol == 'http:' ? http : https).request(options, (res) => {
  let chunks = [];
  ('data', (data) => {
  (data);
  });
  ('end', () => {
  let buffer = (chunks);
  let encoding = ['content-encoding'];
  if (encoding == 'gzip') {
   (buffer, function(err, decoded) {
   resolve(());
   });
  } else if (encoding == 'deflate') {
   (buffer, function(err, decoded) {
   resolve(());
   });
  } else {
   resolve(());
  }
  });
 });
 ('error', (e) => {
  reject(e);
 });
 if (postData != '') {
  (postData);
 }
 ();
 })
}
 = function(url) {
 return ('GET', url, null);
}
 = function(url, params) {
 return ('POST', url, params);
}
 = function(cookie) {
 return new Request(cookie);
}

const request = require('./request')();
(async function() {
 let res = await ('/');
 (res);
})();

Execute the command

nodemon 

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