Adding trusted CA to node client with axios

I had to create a node client which sends a get request with some parameters to a server. The server is using a self signed certificate, so I had to add the CA as trusted on the client side. Here is my solution creating an httpsAgent and using axios. I saved the CA certificate in the project root and named it ca.crt

const https = require('https');
const fs = require('fs');
const axios = require('axios');
const url = 'https://serverurl.com';
let caCrt = '';
try {
caCrt = fs.readFileSync('./ca.crt')
} catch(err) {
console.log('Make sure that the CA cert file is named ca.crt', err);
}
const httpsAgent = new https.Agent({ ca: caCrt, keepAlive: false });
const sendGetReq = (params) => {
axios.get(url, {
params: params,
httpsAgent: httpsAgent
})
.then( res => {
console.log(Date());
console.log('statusCode', res.status);
console.log('Response', res.data);
}).catch( error => console.log(`${Date()} fail: ${url}: ${error}`));
};

If this tutorial helped you, you can thank me by buying me coffee.

--

--

Web development, CS and other stuff

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store