fetch

The fetch API provides a modern interface for making HTTP/HTTPS requests. It returns a Promise resolving to a Response object.


API Surface

fetch(url, [options])

  • url — resource URL.
  • options:
    • method: GET, POST, etc.
    • headers: request headers.
    • body: request body (string, Buffer, stream, FormData).
    • signal: AbortController signal.

Response object

  • Properties:
    • status, ok, headers.
  • Methods:
    • .text(), .json(), .arrayBuffer(), .blob() (in browsers), .formData().
    • .body — readable stream.

Request object

  • Can construct with new Request(url, options).

Headers

  • Headers class with .get(), .set(), .append(), .delete().

Examples (English only)

// Simple GET
const res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await res.json();
console.log(data);

// POST with JSON
const postRes = await fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "Bnlang", body: "Hello", userId: 1 })
});
console.log("status:", postRes.status);

// Streaming response body
const streamRes = await fetch("https://example.com/large-file");
for await (const chunk of streamRes.body) {
  console.log("chunk size:", chunk.length);
}

Notes

  • fetch is Promise-based; use with await or .then().
  • Always check res.ok or res.status before using body.
  • Aborting: use AbortController with signal.
  • In Bnlang runtime, fetch is built-in (no import needed).