Skip to content

https

https เป็นโมดูลในตัวของ Node.js ที่ให้ความสามารถในการสร้าง HTTPS server และ client สำหรับการสื่อสารที่ปลอดภัยผ่านโปรโตคอล HTTP ที่มีการเข้ารหัส

Import

javascript
import { createServer, get, request } from "node:https";

API

APIคำอธิบายลักษณะคำอธิบายเพิ่มเติม
createServerสร้าง HTTPS serverAsynchronousต้องระบุ certificate และ private key สำหรับการเข้ารหัส SSL/TLS
requestสร้าง HTTPS client requestAsynchronousสำหรับส่ง HTTPS requests ไปยัง server อื่น
getส่ง HTTPS GET requestAsynchronousเหมาะสำหรับการส่ง GET requests ที่ไม่ซับซ้อน

ตัวอย่าง

สร้าง HTTPS Server พื้นฐาน

javascript
import { readFileSync } from "fs";
import { createServer } from "https";

// อ่านไฟล์ certificate และ private key
const options = {
  key: readFileSync("server-key.pem"),
  cert: readFileSync("server-cert.pem"),
};

// สร้าง HTTPS server
const server = createServer(options, (req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Secure Connection Established!");
});

server.listen(443, () => {
  console.log("HTTPS Server running on port 443");
});

ส่ง HTTPS Request

javascript
import { get } from "https";

// ส่ง GET request ไปยัง HTTPS endpoint
const req = get("https://example.com", (res) => {
  let data = "";

  res.on("data", (chunk) => {
    data += chunk;
  });

  res.on("end", () => {
    console.log("Response:", data);
  });
});

req.on("error", (err) => {
  console.error("HTTPS Request Error:", err);
});

ใช้ Self-Signed Certificate

javascript
import { readFileSync } from "fs";
import { createServer } from "https";

// สำหรับ development เท่านั้น
const options = {
  key: readFileSync("key.pem"),
  cert: readFileSync("cert.pem"),
  // อนุญาต self-signed certificate
  rejectUnauthorized: false,
};

const server = createServer(options, (req, res) => {
  res.writeHead(200, { "Content-Type": "application/json" });
  res.end(JSON.stringify({ message: "Secure Connection" }));
});

server.listen(8443);

ตรวจสอบ SSL Certificate

javascript
import { request } from "https";

const options = {
  hostname: "example.com",
  port: 443,
  path: "/",
  method: "GET",
  // ตรวจสอบ certificate
  checkServerIdentity: (host, cert) => {
    // ตรวจสอบว่า certificate ตรงกับ hostname หรือไม่
    const err = tls.checkServerIdentity(host, cert);
    if (err) {
      console.error("Certificate Error:", err);
      return err;
    }
  },
};

const req = request(options, (res) => {
  console.log("Status Code:", res.statusCode);
  res.resume();
});

req.end();