const http = require('http')
const https = require('https')
const fs = require('fs');
const Qs = require('qs');
function requireHTTP(url, options, httpRequire) {
const isHttps = url.indexOf('https://') !== -1
const request = isHttps ? https.request : http.request
return new Promise((resolve, reject) => {
const req = request(url, options, (res) => {
// console.log(res.req._header)
let data = ''
res.setEncoding('utf8');
res.on('data', (chunk) => { // data 事件在callbackFn里面
// console.log(chunk);
data += chunk
});
res.on('end', ()=>{ // end 事件在callbackFn里面
resolve(data)
});
});
req.on('error', (e) => {
reject(e)
console.log('error', e.message);
});
if (options.data) {
console.log('data', options.data)
req.write(options.data)
}
req.end();
})
}
requireHTTP('http://127.0.0.1/test', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest',
},
data: Qs.stringify({
formdata: 111
})
}).then(res => {
console.log(res.length);
fs.writeFileSync('./index.html', res)
})
module.exports = {
requireHTTP
}