nodejs实现的http、https 请求封装操作示例
程序员文章站
2022-11-16 12:50:28
本文实例讲述了nodejs实现的http、https 请求封装操作。分享给大家供大家参考,具体如下:libs/request.jsconst url = require('url');const zl...
本文实例讲述了nodejs实现的http、https 请求封装操作。分享给大家供大家参考,具体如下:
libs/request.js
const url = require('url'); const zlib = require('zlib'); const http = require('http'); const https = require('https'); const qs = require('querystring'); function request(cookie) { this.cookies = []; if (cookie !== undefined) { this.setcookie(cookie); } } request.prototype.getheaders = 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 (this.cookies.length) { headers.cookie = this.cookies.join('; '); } if (postdata != '') { headers['content-length'] = buffer.bytelength(postdata); } return headers; } request.prototype.setcookie = function(cookie) { let cookies = cookie.split(';'); for (let c of cookies) { c = c.replace(/^\s/, ''); this.cookies.push(c); } return this; } request.prototype.request = function(method, url, params) { let postdata = qs.stringify(params || {}); let urlobj = url.parse(url); let protocol = urlobj.protocol; let options = { hostname: urlobj.host, port: urlobj.port, path: urlobj.path, method: method, headers: this.getheaders(urlobj.host, postdata), }; return new promise((resolve, reject) => { let req = (protocol == 'http:' ? http : https).request(options, (res) => { let chunks = []; res.on('data', (data) => { chunks.push(data); }); res.on('end', () => { let buffer = buffer.concat(chunks); let encoding = res.headers['content-encoding']; if (encoding == 'gzip') { zlib.gunzip(buffer, function(err, decoded) { resolve(decoded.tostring()); }); } else if (encoding == 'deflate') { zlib.inflate(buffer, function(err, decoded) { resolve(decoded.tostring()); }); } else { resolve(buffer.tostring()); } }); }); req.on('error', (e) => { reject(e); }); if (postdata != '') { req.write(postdata); } req.end(); }) } request.prototype.get = function(url) { return this.request('get', url, null); } request.prototype.post = function(url, params) { return this.request('post', url, params); } module.exports = function(cookie) { return new request(cookie); }
test.js
const request = require('./request')(); (async function() { let res = await request.get('http://www.axita.com.cn/'); console.log(res); })();
执行命令
nodemon test.js
希望本文所述对大家node.js程序设计有所帮助。