I'm writing an app in React Native, and I need to make API requests. The server for that is running on a server with a self-signed SSL certificate, so I need Axios and React Native to make the request and accept the response using a self-signed certificate.
I can't get a certificate from an official certificate authority.
I have already tried using https.Agent, however this doesn't seem to be possible when using React Native (The https module is part of the node standard library, which is not included in React Native), so this is also not a valid solution.
I would prefer to continue using Axios, however I would consider switching libraries if there are any with similar functionality (I've already tried a few, none provided functionality to allow self-signed certs).
Here is some example code from my project (url is the IP of the server):
import axios from 'axios';
const instance = axios.create({ });
instance.get(url)
.then(res => {
this.setState({dataSource: res.data});
})
Btw, when I'm using ngrok everything works fine, so the self-signed certificate is definitely the only problem.
To make API requests using Axios and React Native with a self-signed SSL certificate, you can use the httpsAgent option to specify an instance of the https.Agent class, which allows you to specify custom certificate validation options.
However, as you mentioned, the https module is not available in React Native, so you will need to use a third-party library that provides similar functionality. One option is the https-proxy-agent library, which provides an HTTP(S) agent that uses an HTTP(S) proxy to tunnel traffic to the target host.
Here's an example of how you can use the https-proxy-agent library with Axios to make API requests with a self-signed SSL certificate:
import axios from 'axios'; import HttpsProxyAgent from 'https-proxy-agent'; const httpsAgent = new HttpsProxyAgent({ rejectUnauthorized: false, }); const instance = axios.create({ httpsAgent, }); instance.get(url) .then((res) => { this.setState({ dataSource: res.data }); }) .catch((error) => { console.error(error); });
This code creates an instance of the HttpsProxyAgent class with the rejectUnauthorized option set to false, which allows the agent to accept self-signed SSL certificates. It then passes the agent as the httpsAgent option to the Axios instance.
Keep in mind that this approach may not be secure, as it allows the agent to accept any SSL certificate, even if it is invalid or forged. You should only use it if you are unable to obtain a valid SSL certificate from a trusted certificate authority.