1

I have a curl call that looks like this:

curl \
-v \
-X POST \
-k \
-H 'Content-Type: application/json' \
-d '{
    "mydata": "XXXXX"
}' \
"https://localhost:11000/myEndpoint"

It works. I get a 200 response. But when I remove the -k flag, it fails with this error:

curl: (60) SSL certificate problem: self signed certificate

So I know that the -k flag is required.

Now I'm trying to convert this curl to Javascript/React. But when I do this in React, it fails:

const response = await fetch(
  'https://localhost:11000/myEndpoint',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ mydata: 'XXXXX' })
  },
)

Here is the error in the browser console:

POST https://localhost:11000/myEndpoint net::ERR_CERT_AUTHORITY_INVALID

I believe this error is because the Javascript/React is not doing the equivalent of a -k. How can I make it mimic the -k behavior of Curl?

Saqib Ali
  • 11,931
  • 41
  • 133
  • 272

2 Answers2

3

There's no way to have a fetch() (or XHR, or any other) call directly do what -k (also known as --insecure) does.

You will need to tell your browser to trust that self-signed certificate.

In general, you can do that for a single session by navigating to https://localhost:11000/ and accepting the "Yes, I know what I'm doing, I know this is insecure" prompt that'll likely show up.

For more permanent solutions, you can search the web for e.g. "trust self-signed certificate YOUR BROWSER HERE"...

AKX
  • 152,115
  • 15
  • 115
  • 172
0

AKX's response is correct. Had a similar issue, I believe the way described is valid on chrome. For firefox you have to trust the certificate through the browser.

That being said, you can basically use axios instead of fetch and pass as options:

   httpsAgent: new https.Agent({rejectUnauthorized: false})

However, this will not work if you are using webpack > 5 (will be printed in the console as an error). To make it work in dev environment, you should do the following:

  • Install the packages https, https-browserify, stream-http and include them in webpack.config.js as polyfills:

     resolve: { 
         fallback: {
             "https": require.resolve("https-browserify"),
              "http": require.resolve("stream-http")
         }
     }
    
  • Install also (npm install): buffer, url

  • Run the project and should work

For reasons why this approach should always be avoided in prod (sometimes maybe in dev also) please check the first answer here: How to configure axios to use SSL certificate?

Andreas
  • 416
  • 1
  • 4
  • 8