NodeJS axios fails with self sign certificate while cURL succeeds with same "ca bunlde"

619 Views Asked by At

I am trying to use nodejs with axios library. I use the following code to query some URL:

const tryAxios = async () => {
    const httpsAgent = new https.Agent({
        ca: `${await fs.promises.readFile('/etc/tal_the_king/something.pem', { encoding: 'utf-8' })}`,
        keepAlive: false,
    });

    const x = await axios.get('https://www.example.com', {
        httpssAgent: httpAgent,
        headers: {
            'Cache-Control': 'no-cache',
            'Pragma': 'no-cache',
            'Expires': '0',
        },
    });

    console.log(x);
};

It fails for:

(node:76565) UnhandledPromiseRejectionWarning: Error: self signed certificate in certificate chain
    at TLSSocket.onConnectSecure (_tls_wrap.js:1507:34)
    at TLSSocket.emit (events.js:376:20)
    at TLSSocket.emit (domain.js:470:12)
    at TLSSocket._finishInit (_tls_wrap.js:932:8)
    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:706:12)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:76565) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:76565) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code

Then I try the same with cURL:

sudo curl -v  --cacert '/etc/tal_the_king/something.pem'  https://www.example.com

This query succeeds:

   Trying 93.184.216.34:443...
* Connected to www.example.com (93.184.216.34) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*  CAfile: /etc/tal_the_king/something.pem
*  CApath: none

Where am I wrong?

ThAnK yoU

0

There are 0 best solutions below