JavaScript theorytheory 0/50 · 0%
Async · easy

17. fetch and HTTP

Requests, responses and RPC calls.

`fetch` returns a promise for a `Response`. It rejects only on network failure, so you must check `response.ok` yourself for 4xx/5xx.

const res = await fetch(rpcUrl, {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_blockNumber", params: [] }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const { result } = await res.json();

Check your understanding

  1. 1. Does `fetch` reject on a 500 response?

  2. 2. Which method does JSON-RPC use?

  3. 3. What does `res.json()` return?