Skip to content

在 Bun 中,fetch()unix 選項允許你通過 unix 域套接字 發送 HTTP 請求。

ts
const unix = "/var/run/docker.sock";

const response = await fetch("http://localhost/info", { unix });

const body = await response.json();
console.log(body); // { ... }

unix 選項是一個字符串,用於指定 unix 域套接字的本地文件路徑。fetch() 函數將使用套接字將請求發送到服務器,而不是使用 TCP 網絡連接。https 也支持,只需在 URL 中使用 https:// 協議而不是 http://

要通過 unix 域套接字向 API 端點發送 POST 請求:

ts
const response = await fetch("https://hostname/a/path", {
  unix: "/var/run/path/to/unix.sock",
  method: "POST",
  body: JSON.stringify({ message: "Hello from Bun!" }),
  headers: {
    "Content-Type": "application/json",
  },
});

const body = await response.json();

Bun學習網由www.bunjs.com.cn整理維護