'use strict';
const querystring = require("querystring");
const http = require("http");
function parseCookies(res) {
let list = {};
let ra = res.headers['set-cookie'];
//~ not every response get a `set-cookie`
if (ra) {
ra.forEach((rc) => {
rc && rc.split(';').forEach((cookie) => {
let parts = cookie.split('=');
list[parts.shift().trim()] = parts.join('=');
});
});
}
return list;
}
function packCookie(opts) {
let ar = [];
for (let k in opts) {
ar.push(`${k}=${opts[k]}`);
}
return ar.join("; ");
}
function getResDo(cb) {
return (res) => {
res.setEncoding('utf8');
let rs = '';
res.on('data', (chunk) => {
rs += `${chunk}`;
});
res.on('end', () => {
//console.log("response is %s", resJson);
//console.log(res.headers);
//console.log("====");
//console.log(res.headers.cookie);// undefined
//console.log(res.headers['set-cookie']); // an array
//console.log("Is an array: %s", Array.isArray(res.headers['set-cookie']));
cb(res, rs);
});
};
}
function makeDoGetTo(targetHost, targetPort) {
return (uri, cOpts) => {
return new Promise((resolve, reject) => {
let opts = {
hostname: targetHost,
port: targetPort,
path: uri,
method: 'GET',
headers: {
Cookie: packCookie(cOpts)
}
};
let req = http.request(opts, getResDo((res, rs) => resolve({
response: rs,
cookie: parseCookies(res),
oldCookie: cOpts
})));
req.end();
});
}
}
function makeDoPostTo(targetHost, targetPort) {
return (uri, postdata, cOpts) => {
return new Promise((resolve, reject) => {
let data = querystring.stringify(postdata);
let postOpts = {
hostname: targetHost,
port: targetPort,
path: uri,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': data.length,
Cookie: packCookie(cOpts)
}
};
let req = http.request(postOpts, getResDo(
(res, rs) => resolve({
response: rs,
cookie: parseCookies(res),
oldCookie: cOpts
})
));
req.end(data);
});
}
}
module.exports = {
makeDoGetTo,
makeDoPostTo
};
httputils.js
最新推荐文章于 2024-07-12 11:52:22 发布