api request connection issue in nodejs

I’m trying to make a get request to a web url using basic auth. But it failed with connection issues.

Note: It works when i use ‘request’ library instead of ‘got’

What I’m I missing here ?

const got = require('got');

(async () => {
  try {
    const res = await got( 
                      { 
                        url: 'https://<url>.com',
                        headers: {
                        Accept: 'application/json',
                        Authorization: 'Basic abcjghgh8****'
                      }
                    })
    console.log('statusCode:', res.statusCode);
        console.log('body:', res.body);
    } catch (error) {
        console.log('error:', error);
    }
})();

OUTPUT:

library

1 thought on “api request connection issue in nodejs”

  1. When using got(), if you want the body, then you need to use await got(...).json() or await got(...).text() or whatever option is appropriate to your data type. By default, the body has not yet been read (somewhat like the fetch() interface, but easier to use because you can just directly use the .json() method).

    const got = require('got');
    
    (async () => {
        try {
            const body = await got({
                url: 'some URL here',
                headers: {
                    Accept: 'application/json',
                    Authorization: 'Basic abcjghgh8****'
                }
            }).json(); // add .json() here
            console.log('body:', body);
        } catch (error) {
            console.log('error:', error);
        }
    })();
    

    And, got().json() resolves directly to the body.

    You don’t have to check the statusCode yourself because if it isn’t a 2xx status, then it will reject the promise automatically.

    Reply

Leave a Comment