简中文档
On this page

HTTP 响应

响应 接口是 Fetch API 的一部分,表示 fetch() 的响应资源。

构造函数 Jump to heading

Response() 构造函数创建一个新的 Response 实例。

let response = new Response(body, init);

参数 Jump to heading

名称 类型 可选 描述
body BlobBufferSourceFormDataReadableStreamURLSearchParamsUSVString true 响应的主体。默认值为 null
init ResponseInit true 可选对象,允许设置响应的状态和头部信息。

返回类型为一个 Response 实例。

ResponseInit Jump to heading
名称 类型 可选 描述
status number true 响应的状态码。
statusText string true 表示状态码的状态信息。
headers Headersstring[][]Record<string, string> false 响应的 HTTP 头信息。

属性 Jump to heading

名称 类型 只读 描述
body ReadableStream true getter 返回主体内容的 ReadableStream
bodyUsed boolean true 表示主体内容是否已被读取。
url USVString true 响应的 URL。
headers Headers true 与响应相关的头部信息。
ok boolean true 表示响应是否成功(状态码在 200-299 之间)。
redirected boolean true 表示响应是否是重定向的结果。
status number true 响应的状态码。
statusText string true 响应的状态信息。
type string true 响应的类型。

方法 Jump to heading

名称 描述
arrayBuffer() 读取主体流直到完成并返回一个 ArrayBuffer 对象。
blob() 读取主体流直到完成并返回一个 Blob 对象。
formData() 读取主体流直到完成并返回一个 FormData 对象。
json() 读取主体流直到完成,将其解析为 JSON 并返回一个 JavaScript 对象。
text() 读取主体流直到完成并返回一个 USVString 对象(文本)。
clone() 克隆响应对象。
error() 返回一个与网络错误相关的新响应对象。
redirect(url: string, status?: number) 创建一个新的响应,重定向到提供的 URL。

示例 Jump to heading

function handler(_req) {
  // 创建一个以 HTML 为主体的响应。
  const response = new Response("<html> Hello </html>", {
    status: 200,
    headers: {
      "content-type": "text/html",
    },
  });

  console.log(response.status); // 200
  console.log(response.headers.get("content-type")); // text/html

  return response;
}

Deno.serve(handler);

你找到了你需要的东西吗?

编辑此页面
隐私政策