提供证书时Node标准https和node-fetch的区别

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

ADP 的 REST API 要求随每个请求发送 SSL 证书和私钥。

当我使用标准的 Node.js HTTP(S) 模块时:

require('dotenv').config()

const fs = require('fs')
const path = require('path')

const certificate_path = path.resolve('../credentials/certificate.pem')
const private_key_path = path.resolve('../credentials/private.key')

const options = {
    hostname: 'api.adp.com',
    path: '/hr/v2/workers/ABCDEFGHIJKLMNOP',
    method: 'GET',
    headers: {
        'Accept': 'application/json;masked=false',
        'Authorization': `Bearer ${process.env.ACCESS_TOKEN}`
    },
    cert: fs.readFileSync(certificate_path, "utf8"),
    key: fs.readFileSync(private_key_path, "utf8"),
};

require('https').get(options, res => {

  let data = [];

  res.on('data', chunk => {
    data.push(chunk);
  });

  res.on('end', () => {

    const workers = JSON.parse(Buffer.concat(data).toString());

    for(worker of workers.workers) {
      console.log(`Got worker with id: ${worker.associateOID}, name: ${worker.person.legalName.formattedName}`);
    }

  });

}).on('error', err => {
  console.log('Error: ', err.message);
});

请求按预期工作:

$ node ./standard.js
Got worker with id: ABCDEFGHIJKLMNOP, name: Last, First

但是,当我使用 node-fetch 时:

require('dotenv').config()

const fs = require('fs')
const path = require('path')

const certificate_path = path.resolve('../credentials/certificate.pem')
const private_key_path = path.resolve('../credentials/private.key')

const url = 'https://accounts.adp.com/hr/v2/workers/ABCDEFGHIJKLMNOP'

const options = {
  headers: {
    'Accept': 'application/json;masked=false',
    'Authorization': `Bearer ${process.env.ACCESS_TOKEN}`
  },
  agent: new require('https').Agent({
      cert: fs.readFileSync(certificate_path, "utf8"),
      key: fs.readFileSync(private_key_path, "utf8")
  })
}

fetch(url,options)
  .then((response) => response.json())
  .then((body) => {
      console.log(body);
  });

我得到一个错误:

$ node ./fetch.js   
{
  response: {
    responseCode: 401,
    methodCode: 'GET',
    resourceUri: { href: '/hr/v2/workers/ABCDEFGHIJKLMNOP' },
    serverRequestDateTime: '2023-03-30T14:25:23.351Z',
    applicationCode: {
      code: 401,
      typeCode: 'error',
      message: 'Request did not provide the required two-way TLS certificate'
    },
    client_ip_adddress: 'a.b.c.d',
    'adp-correlationID': '61f76d29-04e1-48b8-be9d-acf459408b2b'
  }
}

第二种方法我错过了什么?

javascript node.js client-certificates node-fetch node-https
1个回答
0
投票

我没有看到 node-fetch 的任何导入,所以我假设您正在使用添加到 Node18 的新本机 fetch。新的全局提取不(还)支持代理选项。

© www.soinside.com 2019 - 2024. All rights reserved.