Categories
JavaScript Answers

How to configure axios to use SSL certificate?

Spread the love

Sometimes, we want to configure axios to use SSL certificate.

In this article, we’ll look at how to configure axios to use SSL certificate.

How to configure axios to use SSL certificate?

To configure axios to use SSL certificate, we set the rejectUnauthorized option to false and add our certificate files as the options for axios.

For instance, we write

const httpsAgent = new https.Agent({
  rejectUnauthorized: false,
  cert: fs.readFileSync("./usercert.pem"),
  key: fs.readFileSync("./key.pem"),
  passphrase: "YYY",
});

axios.get(url, { httpsAgent });

to create the httpsAgent object with the https.Agent constructor.

We set rejectUnauthorized to disable client verification.

And then we add the certificate and private keys by setting the files as the values of cert and key respectively.

We also set the passphrase for the certificate if we have one.

Then we call axios.get or other request methods with httpsAgent in the option object.

We can also create a new axios instance with the httpsAgent with

const instance = axios.create({ httpsAgent });

Conclusion

To configure axios to use SSL certificate, we set the rejectUnauthorized option to false and add our certificate files as the options for axios.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *