javascript 客户端HTTPS相互证书示例,其中o.js位于node.js上

vlju58qv  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(87)

有谁能给出一个在node.js上使用o.js的例子,在提供证书的同时使用HTTPS连接?
我目前有以下直接使用node.js https模块的示例,但我希望使用o.js lib来避免手动创建OData URL:

const https = require("https");
const fs = require("fs");

const requestParams = {
    hostname: "<the hostname>",
    port: 44300,
    key: fs.readFileSync("path/to/client-key.pem"),
    cert: fs.readFileSync("path/to/client-crt.pem"),
    ca: fs.readFileSync("path/to/ca-crt.pem"),
    rejectUnauthorized : false,
    path: "<the OData URL>",
    method: "<GET/POST/DELETE etc>"
};

const httpsReq = https.request(requestParams, httpsRes => {
    // Handle the response here
});

httpsReq.end();
w6lpcovy

w6lpcovy1#

您可以像这样使用它:

const fs = require("fs");
const { OData } = require("o.js");
const fetch = require("node-fetch");
const https = require("https");

// Configure HTTPS agent with the necessary certificates
const httpsAgent = new https.Agent({
  key: fs.readFileSync("path/to/client-key.pem"),
  cert: fs.readFileSync("path/to/client-crt.pem"),
  ca: fs.readFileSync("path/to/ca-crt.pem"),
  rejectUnauthorized: false,
});

// Configure o.js to use node-fetch and the custom HTTPS agent
const odata = new OData({
  endpoint: "https://<the hostname>:44300",
  fetch: (url, options) => {
    options.agent = httpsAgent;
    return fetch(url, options);
  },
});

// Make OData requests using o.js
odata
  .get("<OData Entity Set>")
  .query({
    // Add your OData query options here
  })
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.error(error);
  });

相关问题