HTTP requests

This example demonstrates how to make an HTTP request to a server.

Edit on GitHub

To make a request to a server, you use the `fetch` API.

let resp = await fetch("https://example.com");

The response is a `Response` object. This contains the status code, headers, and the body.

console.log(resp.status); // 200
console.log(resp.headers.get("Content-Type")); // "text/html"
console.log(await resp.text()); // "Hello, World!"

The response body can also be read as JSON, an ArrayBuffer, or a Blob. A body can be read only once.

resp = await fetch("https://example.com");
await resp.arrayBuffer();
/** or await resp.json(); */
/** or await resp.blob(); */

The response body can also be streamed in chunks.

resp = await fetch("https://example.com");

for await (const chunk of resp.body!) {
  console.log("chunk", chunk);
}

When making a request, you can also specify the method, headers, and a body.

resp = await fetch("https://example.com", {
  body: JSON.stringify({
    param: "value"
  }),
  headers: {
    "Content-Type": "application/json",
    "X-API-Key": "foobar"
  },
  method: "POST"
});

`fetch` also accepts a `Request` object instead of URL + options.

const req = new Request("https://example.com", {
  method: "DELETE"
});

resp = await fetch(req);

Instead of a string, the body can also be any typed array, blob, or a URLSearchParams object.

const url = "https://example.com";

new Request(url, {
  body: new Uint8Array([1, 2, 3]),
  method: "POST"
});

new Request(url, {
  body: new Blob(["Hello, World!"]),
  method: "POST"
});

new Request(url, {
  body: new URLSearchParams({ "foo": "bar" }),
  method: "POST"
});

Forms can also be sent with `fetch` by using a `FormData` object as the body.

const formData = new FormData();
formData.append("name", "Ende");
formData.append("file", new Blob(["Hello, World!"]), "hello.txt");

resp = await fetch("https://example.com", {
  body: formData,
  method: "POST"
});

Fetch also supports streaming the request body.

const bodyStream = new ReadableStream({
  start(controller) {
    controller.enqueue(new TextEncoder().encode("Hello, World!"));
    controller.close();
  }
});

resp = await fetch("https://example.com", {
  body: bodyStream,
  method: "POST"
});

Run this example locally using the Ende CLI:

ende run -N https://docs.ende.sh/examples/scripts/http_requests.ts

Additional resources