Axios:使用 httpsAgent 将rejectUnauthorized 设置为 false 以忽略 SSL 问题不适用于 POST 请求

问题描述 投票:0回答:1

我使用 axios 和 NodeJS 来查询 Mikrotik RouterOS 的 REST API,因为你需要强制使用自签名 SSL 证书。 当我运行 GET 请求并添加

httpsAgent: new https.Agent({ rejectUnauthorized: false})
时,一切正常。 但所有其他方法都失败了,我收到此错误:

cause: Error: self-signed certificate in certificate chain
      at TLSSocket.onConnectSecure (node:_tls_wrap:1674:34)
      at TLSSocket.emit (node:events:518:28)
      at TLSSocket._finishInit (node:_tls_wrap:1085:8)
      at ssl.onhandshakedone (node:_tls_wrap:871:12) {
    code: 'SELF_SIGNED_CERT_IN_CHAIN'
  }

我已经尝试过设置

process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;
,但是它给了我一个带有“未经授权”消息的 401 HTTP 代码。

const macAddress= "10-78-D2-F9-12-E7";
const byPassed= "bypassed";


axios.post(`https://192.168.8.1:8082/rest/ip/hotspot/ip-binding`,
    {
        httpsAgent: new https.Agent({ rejectUnauthorized: false}), // Allow Self-signed certificates
        auth: {
            username: "****",
            password: "*****"
          },
          headers: {
            'Content-Type': 'application/json',
        },
        content: JSON.stringify({
            "mac-address": macAddress,
            "type": byPassed,
            
        })
    },
    
    ).then(response => {
        console.log(response.data)
    }).catch(error => {
        console.log(error)
    });

node.js axios ssl-certificate
1个回答
0
投票

真正的问题是我在 post 请求的 axios 语法上犯了一个错误,这就是它不起作用的原因。所以与我修复语法后正在运行的

httpAgent
无关。 我也不需要设置
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0;

在下面找到正确的方法:

const macAddress= "10-78-D2-F9-12-E7";
const byPassed= "bypassed";


axios.post(`https://192.168.8.1:8082/rest/ip/hotspot/ip-binding`,
{
  "mac-address": macAddress,
  "type": byPassed,
}
{
   httpsAgent: new https.Agent({ rejectUnauthorized: false}), // Allow Self- 
   signed certificates
        auth: {
            username: "****",
            password: "*****"
          },
          headers: {
            'Content-Type': 'application/json',
        },
       
    },
    
    ).then(response => {
        console.log(response.data)
    }).catch(error => {
        console.log(error)
    });
© www.soinside.com 2019 - 2024. All rights reserved.