6

因此,标题非常简单。我想使用一家公司的网络服务,我得到了 .cer 和 .p12 文件。据说,我应该在发出请求时使用 .p12 。我已将 .cer 导入 Windows,我可以轻松地向邮递员提出请求。但是当我尝试使用 node.js 发出请求时,我得到了错误。这是代码,我正在使用request模块:

var headersOpt = {
    "content-type": "application/json",
};

var options = {
    url: 'https://some-url/api',
    cert: fs.readFileSync(__dirname + '/certs/myCert.p12'),
    headers: headersOpt
};

request.get(options, (error, response, body) => {
    console.log(error);
    console.log(response);
    console.log(body);
});

我收到此错误:

{ Error: error:0906D06C:PEM routines:PEM_read_bio:no start line
    at Object.createSecureContext (_tls_common.js:89:17)
    at Object.exports.connect (_tls_wrap.js:1048:48)
    at Agent.createConnection (https.js:111:22)
    at Agent.createSocket (_http_agent.js:224:26)
    at Agent.addRequest (_http_agent.js:192:10)
    at new ClientRequest (_http_client.js:256:16)
    at Object.request (http.js:39:10)
    at Object.request (https.js:239:15)
    at Request.start (D:\parser\node_modules\request\request.js:748:32)
    at Request.end (D:\parser\node_modules\request\request.js:1512:10)
  opensslErrorStack:
   [ 'error:140DC009:SSL routines:SSL_CTX_use_certificate_chain_file:PEM lib' ] }
4

2 回答 2

16

使用pkcs12 格式的pfx属性:agentOptions

'use strict';

const request = require('request');
const fs = require('fs');

var options = {
    url: 'https://some-url/api',
    headers: {
        "content-type": "application/json",
    },
    agentOptions: {
        pfx: fs.readFileSync(__dirname + '/certs/myCert.p12'),
        passphrase: ''
    }
};

request.get(options, (error, response, body) => {
    console.log(error);
    console.log(response);
    console.log(body);
});

如果您的证书是自签名的,请检查

于 2017-10-23T16:58:15.667 回答
2

Bertrand Martel 的另一条评论中的请求 API 已被弃用,因此不安全,您也可以使用 axios 来实现相同的目的:

const fs = require('fs');
const axios = require('axios');
const https = require('https');

const response = await axios.request({
    url: *URL_HERE*,
    method: 'post',
    headers: {
        "content-type": "application/json",
    },
    data: JSON.stringify({
        *YOUR_DATA_HERE*
    }),
    httpsAgent: new https.Agent({
        passphrase: *PASSPHRASE_HERE*,
        pfx: fs.readFileSync(__dirname + '\\..\\certificates\\certificate.p12'),
    })
});
于 2021-06-09T19:41:26.380 回答