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
Headersclass 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
awaitor.then(). - Always check
res.okorres.statusbefore using body. - Aborting: use AbortController with
signal. - In Bnlang runtime,
fetchis built-in (no import needed).