Request Constructor Builds Fetch Inputs

Create a Request from a URL and options, clone it before reading the body, and inspect method, headers, and cache mode without sending traffic.

JavascriptData Fetching

Code

javascriptsnippet
28 lines
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();

How it works

Request Constructor Builds Fetch Inputs is built around the function main.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Putting it to use

Entry signature: async function main()

The run emits 7 labeled sections — url:, method:, content type:, trace:, cache:, payload:, body used: — one per step.

Core lines

const payload = await copy.json();

Interactive Tools for This Topic

FAQ

What does Request Constructor Builds Fetch Inputs print when run?
Invoke the file as-is — the `url:`, `method:`, `content type:` prefixes identify which step printed each line.