Node.js使用.p12证书请求Web服务 [英] Nodejs request to a web service with .p12 certificate

查看:644
本文介绍了Node.js使用.p12证书请求Web服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So, the title is pretty straightforward. I want to consume a web service from a company and I got .cer and .p12 files. Supposedly, I should use .p12 when making a request. I've imported .cer into windows and I can make requests with postman easily. But when I'm trying to do a request with node.js, I get errors. Here's the code, I'm using request module:

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' ] }

推荐答案

中使用pfx属性agentOptions 用于pkcs12格式:

Use pfx property in agentOptions for pkcs12 format :

'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);
});

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

If your certificate is self signed, check this

这篇关于Node.js使用.p12证书请求Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆