1. const http = require('http')
    2. const https = require('https')
    3. const fs = require('fs');
    4. const Qs = require('qs');
    5. function requireHTTP(url, options, httpRequire) {
    6. const isHttps = url.indexOf('https://') !== -1
    7. const request = isHttps ? https.request : http.request
    8. return new Promise((resolve, reject) => {
    9. const req = request(url, options, (res) => {
    10. // console.log(res.req._header)
    11. let data = ''
    12. res.setEncoding('utf8');
    13. res.on('data', (chunk) => { // data 事件在callbackFn里面
    14. // console.log(chunk);
    15. data += chunk
    16. });
    17. res.on('end', ()=>{ // end 事件在callbackFn里面
    18. resolve(data)
    19. });
    20. });
    21. req.on('error', (e) => {
    22. reject(e)
    23. console.log('error', e.message);
    24. });
    25. if (options.data) {
    26. console.log('data', options.data)
    27. req.write(options.data)
    28. }
    29. req.end();
    30. })
    31. }
    32. requireHTTP('http://127.0.0.1/test', {
    33. method: 'POST',
    34. headers: {
    35. 'Content-Type': 'application/x-www-form-urlencoded',
    36. 'X-Requested-With': 'XMLHttpRequest',
    37. },
    38. data: Qs.stringify({
    39. formdata: 111
    40. })
    41. }).then(res => {
    42. console.log(res.length);
    43. fs.writeFileSync('./index.html', res)
    44. })
    45. module.exports = {
    46. requireHTTP
    47. }