![](/img/trans.png)
[英]Node.js POST causes [Error: socket hang up] code: 'ECONNRESET'
[英]Curl to Axios in Node.js - Problem with implementing working curl request with provided certificates - ECONNRESET / Socket hang up error
我一直在嘗試在 Axios (Node.js) 中實現工作 curl 請求,但沒有成功。
工作 curl 請求看起來像這樣(我不能分享確切的請求,因為 API 是私有的):
curl --cacert server.pem --cert client.pem:123password456 -i -H "accept:application/json" -H "content-Type:application/json" "https://example.endpoint.com/"
所以我有這兩個文件,服務器證書server.pem
和客戶端證書client.pem
,密碼123password456
。 當我運行這個 curl 請求時,我得到了成功的響應(200 OK)。 但是,我在 Node.js 中的 Axios 實現並非如此。 我在節點中的 axios 請求如下所示:
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/");
當我在 Node 中運行上面的代碼時,它立即拋出 Axios 錯誤:
Error: socket hang up\n at connResetException (node:internal/errors:691:14)...
Error object:
{
code:'ECONNRESET'
message:'socket hang up'
isAxiosError:true
...
}
我已經嘗試過各種編輯(例如不使用 axios 實例並僅使用 axios 對象)。 非常感謝您的幫助
我自己設法解決了問題。 檢查證書文件后,我發現提供的客戶端證書文件client.pem
包含客戶端證書和私鑰。 使用 https 模塊創建的 Https agent 需要單獨指定私鑰為key
,修改后httpsAgent
應該是這樣的:
const httpsAgent = new https.Agent({
cert: fs.readFileSync("./client.pem"),
key: fs.readFileSync("./key.pem"),
passphrase: "123password456",
ca: fs.readFileSync("./server.pem"),
rejectUnauthorized: false
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.