deno.com

HTTP 请求

在 Github 上编辑

此示例演示如何向服务器发出 HTTP 请求。

要向服务器发出请求,请使用 `fetch` API。
let resp = await fetch("https://example.com");
响应是一个 `Response` 对象。它包含状态码、标头和正文。
console.log(resp.status); // 200
console.log(resp.headers.get("Content-Type")); // "text/html"
console.log(await resp.text()); // "Hello, World!"
响应正文也可以读取为 JSON、ArrayBuffer 或 Blob。正文只能读取一次。
resp = await fetch("https://example.com");
await resp.arrayBuffer();
/** or await resp.json(); */
/** or await resp.blob(); */
响应正文也可以分块流式传输。
resp = await fetch("https://example.com");
for await (const chunk of resp.body!) {
  console.log("chunk", chunk);
}
发出请求时,您还可以指定方法、标头和正文。
resp = await fetch("https://example.com", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "X-API-Key": "foobar",
  },
  body: JSON.stringify({
    param: "value",
  }),
});
`fetch` 也接受 `Request` 对象,而不是 URL + 选项。
const req = new Request("https://example.com", {
  method: "DELETE",
});
resp = await fetch(req);
正文也可以是任何类型化数组、blob 或 URLSearchParams 对象,而不是字符串。
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" }),
});
也可以使用 `FormData` 对象作为正文,通过 `fetch` 发送表单。
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 还支持流式传输请求正文。
const bodyStream = new ReadableStream({
  start(controller) {
    controller.enqueue(new TextEncoder().encode("Hello, World!"));
    controller.close();
  },
});
resp = await fetch("https://example.com", {
  method: "POST",
  body: bodyStream,
});

使用 Deno CLI 在本地运行 此示例

deno run --allow-net https://docs.deno.org.cn/examples/scripts/http_requests.ts

您找到所需的内容了吗?

隐私政策