Beginner
clideployweb
HTTP Requests
This example demonstrates how to make a HTTP request to a server.
To make a request to a server, you use the `fetch` API.
!--frsh-copybutton:1-->
let resp = await fetch("https://example.com");
The response is a `Response` object. This contains the status code, headers, and the body.
!--frsh-copybutton:2-->
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.
!--frsh-copybutton:3-->
resp = await fetch("https://example.com");
await resp.arrayBuffer();
/** or await response2.json(); */
/** or await response2.blob(); */
The response body can also be streamed in chunks.
!--frsh-copybutton:4-->
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.
!--frsh-copybutton:5-->
const body = `{"name": "Deno"}`;
resp = await fetch("https://example.com", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-API-Key": "foobar",
},
body,
});
`fetch` also accepts a `Request` object instead of URL + options.
!--frsh-copybutton:6-->
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.
!--frsh-copybutton:7-->
const url = "https://example.com";
new Request(url, {
method: "POST",
body: new Uint8Array([1, 2, 3]),
});
new Request(url, {
method: "POST",
body: new Blob(["Hello, World!"]),
});
new Request(url, {
method: "POST",
body: new URLSearchParams({ "foo": "bar" }),
});
Forms can also be sent with `fetch` by using a `FormData` object as the body.
!--frsh-copybutton:8-->
const formData = new FormData();
formData.append("name", "Deno");
formData.append("file", new Blob(["Hello, World!"]), "hello.txt");
resp = await fetch("https://example.com", {
method: "POST",
body: formData,
});
Fetch also supports streaming the request body.
!--frsh-copybutton:9-->
const bodyStream = new ReadableStream({
start(controller) {
controller.enqueue("Hello, World!");
controller.close();
},
});
resp = await fetch("https://example.com", {
method: "POST",
body: bodyStream,
});
Run this example locally using the Deno CLI:
deno run --allow-net https://byexample-wwv03xf36j0g.deno.dev/http-requests.ts
Additional resources: