HTTP 请求
此示例演示了如何向服务器发起 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 -N https://docs.deno.org.cn/examples/scripts/http_requests.ts