I have been trying to implement working curl request in Axios (Node.js) but with no success.
Working curl request looks like this (I can't share exact request as API is private):
curl --cacert server.pem --cert client.pem:123password456 -i -H "accept:application/json" -H "content-Type:application/json" "https://example.endpoint.com/"
So I have these two files, server certificate server.pem
and client certificate client.pem
with password 123password456
. When I run this curl request, I get successful response (200 OK). However, that is not the case with my Axios implementation in Node.
My axios request in node looks like this:
const axios = require("axios");
const https = require("https");
const fs = require("fs");
const httpsAgent = new https.Agent({
cert: fs.readFileSync("./client.pem"),
passphrase: "123password456",
ca: fs.readFileSync("./server.pem"),
rejectUnauthorized: false
});
const axiosInstance = axios.create({
httpsAgent: httpsAgent
});
// Error on following line called in async function
let response = await axiosInstance.get("https://example.endpoint.com/");
When I run the code above in Node, it instantly throws Axios error:
Error: socket hang up\n at connResetException (node:internal/errors:691:14)...
Error object:
{
code:'ECONNRESET'
message:'socket hang up'
isAxiosError:true
...
}
I have tried it with various edits (for example not using axios instance and using only axios object). Thank you very much for any help
CodePudding user response:
I have managed to resolve issue myself. After inspecting certificate files I found out that the provided client certificate file client.pem
contained both client certificate and private key. Https agent created with https module requires private key to be specified separately as key
, modified httpsAgent
should look like this:
const httpsAgent = new https.Agent({
cert: fs.readFileSync("./client.pem"),
key: fs.readFileSync("./key.pem"),
passphrase: "123password456",
ca: fs.readFileSync("./server.pem"),
rejectUnauthorized: false
});