← 中文资源

简体中文版本

Request 构造器构建请求输入

用 URL 与选项创建 Request,在读取正文前克隆副本,并在不发请求的情况下检查方法、头部与缓存模式。

阅读英文原文

实现说明

Request 构造器构建请求输入可以归结为函数 main。 异步边界用 await 处理,失败以 rejected promise 的形式在调用点浮出,不会被静默吞掉。

使用要点

  • 演示输出是带标签的(url:、method:、content type:),每个操作都会留下自己的一行标注。

常见问题

运行「Request 构造器构建请求输入」会打印什么?

运行文件本身,url:、method:、content type: 这些前缀各对应一段演示逻辑。

主签名形如 async function main()

核心语句

const payload = await copy.json();

代码示例

async function main() {
  // Request is the input object that fetch accepts.
  const request = new Request(
    "https://api.example.com/orders?status=open",
    {
      method: "POST",
      headers: {
        "content-type": "application/json",
        "x-trace-id": "trace-42",
      },
      body: JSON.stringify({ item: "keyboard", quantity: 2 }),
      cache: "no-store",
    },
  );

  console.log("url:", request.url);
  console.log("method:", request.method);
  console.log("content type:", request.headers.get("content-type"));
  console.log("trace:", request.headers.get("x-trace-id"));
  console.log("cache:", request.cache);

  const copy = request.clone();
  const payload = await copy.json();
  console.log("payload:", payload);
  console.log("body used:", request.bodyUsed, copy.bodyUsed);
}

main();