nodejs - http/https request asynchronous

Asked

Viewed 23 times

0

I am trying to assemble a module containing a function of http/https request based on the URL informed, but in the main module I get no output.

get js.

const https = require('https')
const http = require('http')

async function makeRequest(url) {
    var agent = (url.includes("https")) ? https : http
    return new Promise(function(resolve, reject) {
        var body = ''
        const req = agent
        .get(url,  (res) => {
            res.on('data', (data) => {  
                body += data
            });
        })
        resolve(body)
    })
}

module.exports.makeRequest = makeRequest

index js.

const get = require('./get')

async function pegarDados() {
    var resp = await get.makeRequest('http://brasil.io/api/dataset/covid19/caso/data/?city=Ribeir%C3%A3o+Preto&format=json&is_last=True&state=SP')
    console.log(resp)
}

pegarDados()

The schematics are correct?

  • @Rafaeltavares then, without using async I even managed... but this way I’m trying not to go.. I wanted to understand the reason why...

  • The answer to the other question uses http.request(), nay http.get()

  • 1

    I managed using the request method instead of get.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.