Node.js: effettuare richieste HTTP o HTTPS GET

Node.js: effettuare richieste HTTP o HTTPS GET

In questo articolo vedremo come effettuare richieste HTTP o HTTPS GET in Node.js.

Possiamo creare una funzione di utility che accetti sia il protocollo HTTP che HTTPS.


'use strict';

const get = url => {
    
    return new Promise((resolve, reject) => {
        try {
            const urlObj = new URL(url);
            const protocol = urlObj.protocol;

            if(!/^https?$/.test(protocol)) {
                reject('Invalid protocol');
            }

            const module = require(protocol);

            module.get(url, resp => {
                let data = '';
                resp.on('data', chunk => {
                    data += chunk;
                });
                resp.on('end', () => {
                    resolve(data);
                });
            }).on('error', err => {
                reject(err.message);
            });
        } catch(err) {
            reject('Invalid URL');
        }
        
    });
};

Torna su