JavaScript Fetch API: GET, POST, Headers, Errors and Timeouts

fetch is the built-in way to make HTTP requests in JavaScript, in every browser and in Node.js 18 and later, with no library needed. Testers use it constantly: to create test data through an API before a UI test, to check endpoints directly, and to clean up afterwards. In this lesson you will make GET and POST requests, send JSON and headers, build query strings safely, handle HTTP errors correctly (fetch does not reject on 404!), add timeouts, and build a small API client with tests. Every example starts its own tiny local server, so all outputs are real.

Advertisement

📖 What You’ll Learn: what fetch is, GET requests, the Response object (status, ok, headers), reading bodies with json() and text(), why 404 does not reject, POST, PUT, PATCH and DELETE with JSON bodies, headers and authorization, query strings with URL and URLSearchParams, network errors, timeouts and cancellation with AbortSignal, and building a small API client and test suite.


🌐 What Is fetch?

Definition: fetch(url, options) sends an HTTP request and returns a promise that resolves to a Response object as soon as the response headers arrive. Reading the body (response.json(), response.text()) is a second asynchronous step that returns another promise.

The examples below create a small local HTTP server with Node.js’s built-in http module, listen on a free port, send requests to it, then close it. In your own code you would simply call a real API URL.

📄 get.js

const http = require("node:http");

const server = http.createServer((req, res) => {
  res.writeHead(200, { "content-type": "application/json", "x-request-id": "req-42" });
  res.end(JSON.stringify({ id: 7, name: "Asha", role: "tester" }));
});

server.listen(0, async () => {
  const base = `http://127.0.0.1:${server.address().port}`;

  const response = await fetch(`${base}/api/users/7`);   // 1. request, wait for headers
  console.log(response.status, response.statusText, response.ok);
  console.log(response.headers.get("content-type"), response.headers.get("x-request-id"));

  const user = await response.json();                     // 2. read and parse the body
  console.log(user);

  server.close();
});

⌨️ Terminal

node get.js

🖥️ Output

200 OK true
application/json req-42
{ id: 7, name: 'Asha', role: 'tester' }
  • fetch is a global in Node.js 18+ and in browsers; no import is needed.
  • Two awaits are needed: one for the response, one for the body.
  • response.ok is true for status codes 200–299.

📦 The Response Object

Property / methodGives you
status, statusTextThe HTTP status, e.g. 201 and "Created"
oktrue when status is 200–299
headers.get(name)A response header (names are case-insensitive)
url, redirectedThe final URL and whether redirects happened
await json()The body parsed as JSON
await text()The body as a string
await arrayBuffer() / blob()Binary bodies such as images and files

A body can be read only once. If you need it twice (for example to log the raw text and then parse it), read it as text and call JSON.parse yourself, or call response.clone() first:

📄 body-once.js

const http = require("node:http");

const server = http.createServer((req, res) => res.end('{"status":"ok"}'));

server.listen(0, async () => {
  const base = `http://127.0.0.1:${server.address().port}`;
  const res = await fetch(base);
  const text = await res.text();
  console.log("raw:", text, "| parsed:", JSON.parse(text).status);

  try {
    await res.json();                      // second read of the same body
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }
  server.close();
});

⌨️ Terminal

node body-once.js

🖥️ Output

raw: {"status":"ok"} | parsed: ok
TypeError: Body is unusable: Body has already been read

⚠️ fetch Does Not Reject on HTTP Errors

This surprises almost everyone: a 404 or 500 response is still a successful fetch, because the server did answer. fetch only rejects when there is no response at all (network failure, DNS error, refused connection, aborted request). You must check response.ok or response.status yourself.

📄 http-errors.js

const http = require("node:http");

const server = http.createServer((req, res) => {
  if (req.url === "/api/users/99") {
    res.writeHead(404, { "content-type": "application/json" });
    return res.end(JSON.stringify({ error: "User 99 not found" }));
  }
  res.writeHead(500);
  res.end("Internal Server Error");
});

server.listen(0, async () => {
  const base = `http://127.0.0.1:${server.address().port}`;

  const res404 = await fetch(`${base}/api/users/99`);   // no exception!
  console.log("404 resolved:", res404.status, res404.ok, await res404.json());

  const res500 = await fetch(`${base}/api/crash`);
  console.log("500 resolved:", res500.status, res500.ok, await res500.text());
  server.close();
});

⌨️ Terminal

node http-errors.js

🖥️ Output

404 resolved: 404 false { error: 'User 99 not found' }
500 resolved: 500 false Internal Server Error

⚠️ Watch out: Code such as const data = await (await fetch(url)).json() with no status check happily continues with an error body like { error: "..." }, and the test fails later with a confusing message. Always check response.ok first, or use a helper that throws (shown below).


Advertisement

📤 POST, PUT, PATCH and DELETE with JSON

Pass an options object as the second argument: method, headers and body. For JSON, stringify the body and set the content-type header:

📄 post.js

const http = require("node:http");

const server = http.createServer(async (req, res) => {
  let raw = "";
  for await (const chunk of req) raw += chunk;          // read the request body
  const body = raw ? JSON.parse(raw) : null;
  res.writeHead(req.method === "POST" ? 201 : 200, { "content-type": "application/json" });
  res.end(JSON.stringify({ method: req.method, url: req.url, contentType: req.headers["content-type"] ?? null, received: body }));
});

server.listen(0, async () => {
  const base = `http://127.0.0.1:${server.address().port}`;
  const json = { "content-type": "application/json" };

  const created = await fetch(`${base}/api/users`, {
    method: "POST",
    headers: json,
    body: JSON.stringify({ name: "Asha", role: "tester" }),
  });
  console.log(created.status, await created.json());

  const patched = await fetch(`${base}/api/users/7`, { method: "PATCH", headers: json, body: JSON.stringify({ role: "lead" }) });
  console.log(patched.status, (await patched.json()).received);

  const deleted = await fetch(`${base}/api/users/7`, { method: "DELETE" });
  console.log(deleted.status, (await deleted.json()).method);
  server.close();
});

⌨️ Terminal

node post.js

🖥️ Output

201 {
  method: 'POST',
  url: '/api/users',
  contentType: 'application/json',
  received: { name: 'Asha', role: 'tester' }
}
200 { role: 'lead' }
200 DELETE
MethodTypical meaningTypical success status
GETRead a resource200
POSTCreate a resource201
PUTReplace a resource200 or 204
PATCHPartially update a resource200
DELETEDelete a resource200 or 204

💡 Tip: Forgetting JSON.stringify sends the text "[object Object]"; forgetting the content-type header makes many servers ignore the body. Both lead to confusing 400 errors.


🔑 Headers and Authorization

Send headers as a plain object (or a Headers instance). Most APIs expect a token in the authorization header:

📄 auth.js

const http = require("node:http");

const server = http.createServer((req, res) => {
  if (req.headers.authorization !== "Bearer test-token-123") {
    res.writeHead(401, { "content-type": "application/json" });
    return res.end(JSON.stringify({ error: "Unauthorized" }));
  }
  res.writeHead(200, { "content-type": "application/json" });
  res.end(JSON.stringify({ orders: [101, 102], acceptLanguage: req.headers["accept-language"] }));
});

server.listen(0, async () => {
  const base = `http://127.0.0.1:${server.address().port}`;

  const anonymous = await fetch(`${base}/api/orders`);
  console.log("without token:", anonymous.status, await anonymous.json());

  const authed = await fetch(`${base}/api/orders`, {
    headers: { authorization: "Bearer test-token-123", "accept-language": "en-IN" },
  });
  console.log("with token:", authed.status, await authed.json());
  server.close();
});

⌨️ Terminal

node auth.js

🖥️ Output

without token: 401 { error: 'Unauthorized' }
with token: 200 { orders: [ 101, 102 ], acceptLanguage: 'en-IN' }

⚠️ Watch out: Keep tokens out of source code and logs. Read them from environment variables (process.env.API_TOKEN) and redact them before printing requests.


🔗 Building URLs and Query Strings Safely

Build URLs with the URL and URLSearchParams classes instead of string concatenation; they encode spaces, & and other special characters correctly:

📄 url.js

const url = new URL("/api/search", "https://qa.example.com");
url.searchParams.set("q", "usb cable & charger");
url.searchParams.set("page", 2);
url.searchParams.append("tag", "sale");
url.searchParams.append("tag", "new");

console.log(url.href);
console.log(url.searchParams.get("q"), url.searchParams.getAll("tag"));

const params = new URLSearchParams({ sort: "price desc", inStock: "true" });
console.log(`https://qa.example.com/api/products?${params}`);

⌨️ Terminal

node url.js

🖥️ Output

https://qa.example.com/api/search?q=usb+cable+%26+charger&page=2&tag=sale&tag=new
usb cable & charger [ 'sale', 'new' ]
https://qa.example.com/api/products?sort=price+desc&inStock=true

Advertisement

💥 Network Errors and Timeouts

When there is no response at all, fetch rejects with a TypeError: fetch failed; the real reason is in error.cause:

📄 network-error.js

const http = require("node:http");

const server = http.createServer();
server.listen(0, async () => {
  const port = server.address().port;
  server.close();                                   // nothing is listening any more

  try {
    await fetch(`http://127.0.0.1:${port}/health`);
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
    console.log("cause:", e.cause?.code);
  }
});

⌨️ Terminal

node network-error.js

🖥️ Output

TypeError: fetch failed
cause: ECONNREFUSED

A request to a slow or hanging server can wait for a very long time. Pass signal: AbortSignal.timeout(ms) to give up after a limit; the request is really cancelled and fetch rejects with a TimeoutError:

📄 timeout.js

const http = require("node:http");

const server = http.createServer((req, res) => {
  setTimeout(() => res.end("finally"), 2000);       // a very slow endpoint
});

server.listen(0, async () => {
  const base = `http://127.0.0.1:${server.address().port}`;
  try {
    await fetch(`${base}/api/report`, { signal: AbortSignal.timeout(100) });
  } catch (e) {
    console.log(`${e.name}: ${e.message}`);
  }
  server.closeAllConnections();
  server.close();
});

⌨️ Terminal

node timeout.js

🖥️ Output

TimeoutError: The operation was aborted due to timeout
Situationfetch resultHow to detect
2xx responseResolvesresponse.ok === true
4xx / 5xx responseResolvesresponse.ok === false, check status
Server down, DNS failure, refused connectionRejectsTypeError: fetch failed, see error.cause
Timed out with AbortSignal.timeoutRejectserror.name === "TimeoutError"
Cancelled with controller.abort()Rejectserror.name === "AbortError"

🧪 Tester Scenario: A Small API Client and Test Suite

This client wraps fetch once, with JSON handling, a timeout and an ApiError that carries the status and body, so every test gets a clear failure message. The tests then create, read and verify data against a local fake API:

📄 api-tests.js

const http = require("node:http");

// ---- a tiny in-memory API to test against ----
const users = new Map();
let nextId = 1;
const server = http.createServer(async (req, res) => {
  const send = (status, body) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(body)); };
  let raw = "";
  for await (const c of req) raw += c;
  const match = req.url.match(/^\/api\/users\/(\d+)$/);
  if (req.method === "POST" && req.url === "/api/users") {
    const data = JSON.parse(raw);
    if (!data.email?.includes("@")) return send(400, { error: "email is invalid" });
    const user = { id: nextId++, ...data };
    users.set(user.id, user);
    return send(201, user);
  }
  if (req.method === "GET" && match) {
    const user = users.get(Number(match[1]));
    return user ? send(200, user) : send(404, { error: `user ${match[1]} not found` });
  }
  send(404, { error: "no such route" });
});

// ---- the API client ----
class ApiError extends Error {
  constructor(method, path, status, body) {
    super(`${method} ${path} failed with ${status}: ${JSON.stringify(body)}`);
    this.name = "ApiError";
    this.status = status;
  }
}
class ApiClient {
  constructor(baseURL) { this.baseURL = baseURL; }
  async request(method, path, body) {
    const res = await fetch(new URL(path, this.baseURL), {
      method,
      headers: body ? { "content-type": "application/json" } : {},
      body: body ? JSON.stringify(body) : undefined,
      signal: AbortSignal.timeout(2000),
    });
    const data = await res.json();
    if (!res.ok) throw new ApiError(method, path, res.status, data);
    return { status: res.status, data };
  }
}

// ---- the tests ----
async function test(name, fn) {
  try { await fn(); console.log(`✓ ${name}`); }
  catch (e) { console.log(`✗ ${name}\n    ${e.message}`); }
}

server.listen(0, async () => {
  const api = new ApiClient(`http://127.0.0.1:${server.address().port}`);

  await test("creates a user", async () => {
    const { status, data } = await api.request("POST", "/api/users", { name: "Asha", email: "asha@sqatools.in" });
    if (status !== 201 || data.id !== 1) throw new Error(`unexpected ${status} ${JSON.stringify(data)}`);
  });
  await test("reads the created user", async () => {
    const { data } = await api.request("GET", "/api/users/1");
    if (data.email !== "asha@sqatools.in") throw new Error(`wrong email ${data.email}`);
  });
  await test("rejects an invalid email with 400", async () => {
    try {
      await api.request("POST", "/api/users", { name: "Bad", email: "nope" });
      throw new Error("expected a 400 error");
    } catch (e) {
      if (!(e instanceof ApiError) || e.status !== 400) throw e;
    }
  });
  await test("reads a user that does not exist (deliberately failing)", async () => {
    await api.request("GET", "/api/users/99");
  });

  server.close();
});

⌨️ Terminal

node api-tests.js

🖥️ Output

✓ creates a user
✓ reads the created user
✓ rejects an invalid email with 400
✗ reads a user that does not exist (deliberately failing)
    GET /api/users/99 failed with 404: {"error":"user 99 not found"}

The last test fails on purpose to show the message an ApiError produces: method, path, status and the server’s error body in one line. Playwright’s request fixture (request.get(), request.post()) follows the same ideas with built-in base URLs and assertions such as expect(response).toBeOK().


Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Start a local server that returns {"message":"pong"}, fetch it and print the status and the message.

Show answer

📄 practice1.js

const http = require("node:http");
const server = http.createServer((req, res) => res.end(JSON.stringify({ message: "pong" })));
server.listen(0, async () => {
  const res = await fetch(`http://127.0.0.1:${server.address().port}/ping`);
  console.log(res.status, (await res.json()).message);
  server.close();
});

🖥️ Output

200 pong

Q2. Write getJSON(url) that throws an Error containing the status when response.ok is false, and returns the parsed body otherwise. Test it with a 200 and a 404 route.

Show answer

📄 practice2.js

const http = require("node:http");
async function getJSON(url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`GET ${new URL(url).pathname} -> ${res.status}`);
  return res.json();
}
const server = http.createServer((req, res) => {
  res.writeHead(req.url === "/ok" ? 200 : 404);
  res.end(JSON.stringify({ route: req.url }));
});
server.listen(0, async () => {
  const base = `http://127.0.0.1:${server.address().port}`;
  console.log(await getJSON(`${base}/ok`));
  try { await getJSON(`${base}/missing`); } catch (e) { console.log(e.message); }
  server.close();
});

🖥️ Output

{ route: '/ok' }
GET /missing -> 404

Q3. Send a POST request with the JSON body { title: "Login bug", severity: "high" } to a local server that echoes the body back, and print the echoed title.

Show answer

📄 practice3.js

const http = require("node:http");
const server = http.createServer(async (req, res) => {
  let raw = "";
  for await (const c of req) raw += c;
  res.writeHead(201, { "content-type": "application/json" });
  res.end(raw);
});
server.listen(0, async () => {
  const res = await fetch(`http://127.0.0.1:${server.address().port}/bugs`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({ title: "Login bug", severity: "high" }),
  });
  console.log(res.status, (await res.json()).title);
  server.close();
});

🖥️ Output

201 Login bug

Q4. Build the URL https://api.example.com/search with the query parameters q=red shoes and size=9 using URL.

Show answer

📄 practice4.js

const url = new URL("https://api.example.com/search");
url.searchParams.set("q", "red shoes");
url.searchParams.set("size", "9");
console.log(url.toString());

🖥️ Output

https://api.example.com/search?q=red+shoes&size=9

Q5. Fetch three local routes in parallel with Promise.all and print their status codes.

Show answer

📄 practice5.js

const http = require("node:http");
const server = http.createServer((req, res) => {
  res.writeHead({ "/a": 200, "/b": 204, "/c": 404 }[req.url] ?? 500);
  res.end();
});
server.listen(0, async () => {
  const base = `http://127.0.0.1:${server.address().port}`;
  const responses = await Promise.all(["/a", "/b", "/c"].map((p) => fetch(base + p)));
  console.log(responses.map((r) => r.status));
  server.close();
});

🖥️ Output

[ 200, 204, 404 ]

Q6. Explain why this code reports “Saved!” even though the server returned 500, and fix it.

try {
  await fetch(url, { method: "POST", body });
  console.log("Saved!");
} catch {
  console.log("Save failed");
}
Show answer

fetch resolves for any HTTP response, including 500, so the catch never runs. Check the status:

📄 practice6.js

const http = require("node:http");
const server = http.createServer((req, res) => { res.writeHead(500); res.end(); });
server.listen(0, async () => {
  const url = `http://127.0.0.1:${server.address().port}/save`;
  try {
    const res = await fetch(url, { method: "POST", body: "{}" });
    if (!res.ok) throw new Error(`Save failed with ${res.status}`);
    console.log("Saved!");
  } catch (e) {
    console.log(e.message);
  }
  server.close();
});

🖥️ Output

Save failed with 500

🧠 MCQ Quiz: Fetch API

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What does fetch return?
  2. Does fetch reject when the server returns 404?
  3. What is response.ok for status 201?
  4. How do you send a JSON body with fetch?
  5. What happens if you call response.json() twice?
  6. What error does fetch throw when the server is down?
  7. How do you give up on a request after 5 seconds?
  8. Which is the safest way to add query parameters?
  9. Which HTTP method usually creates a resource and returns 201?
  10. Is fetch available in Node.js without installing a package?

💼 Interview Questions and Answers

Q1. How do you handle errors with fetch?

There are two kinds. HTTP errors (4xx, 5xx) resolve normally, so check response.ok or response.status and throw a descriptive error (including the status and response body) when it is not what you expect. Network-level failures (DNS, refused connection, CORS in browsers, timeouts and aborts) reject the promise, so wrap the call in try...catch. Centralise both in one client function so every caller gets consistent errors.

Q2. How do you set a timeout on a fetch request?

Pass an abort signal: fetch(url, { signal: AbortSignal.timeout(5000) }). The request is cancelled after 5 seconds and the promise rejects with a TimeoutError. For manual cancellation use an AbortController and call controller.abort(); combine several signals with AbortSignal.any([...]).

Q3. Why would a tester use fetch or an API client inside UI tests?

To set up and tear down state quickly and reliably: create users, products or orders through the API instead of clicking through forms, log in once and reuse the token, verify that a UI action really changed data on the server, and delete test data afterwards. API setup makes UI tests faster and less flaky because they only exercise the UI being tested.

Q4. What is the difference between response.json() and JSON.parse(await response.text())?

They produce the same object for valid JSON. Reading the text first lets you log or attach the raw body when parsing fails (for example when the server returns an HTML error page), which makes failures easier to diagnose. Both consume the body, which can be read only once unless you clone() the response.


Advertisement

❓ Frequently Asked Questions

🤔 Does fetch work in Node.js?

Yes. Since Node.js 18 fetch, Request, Response, Headers and FormData are available globally, based on the Undici HTTP client.

🤔 What is CORS and does it affect fetch in Node.js?

CORS is a browser security rule that blocks web pages from reading responses from other origins unless the server allows it. Node.js scripts and Playwright’s request fixture are not subject to CORS.

🤔 Should I use axios instead of fetch?

For most testing needs, fetch is enough and has no dependency. Libraries such as axios add conveniences (automatic JSON, interceptors, throwing on HTTP errors), which you can also build with a small wrapper.

🤔 How do I upload a file with fetch?

Create a FormData, append the file (a Blob or File) and other fields, and pass it as body; fetch sets the multipart content-type header for you.


🏁 Summary

  • fetch(url, options) resolves to a Response; read the body once with json() or text().
  • HTTP errors (404, 500) do not reject: always check response.ok or response.status.
  • Send JSON with method, a content-type header and JSON.stringify(body); add tokens in the authorization header.
  • Build URLs with URL and URLSearchParams; use AbortSignal.timeout for timeouts.
  • Wrap fetch in a small API client that throws descriptive errors, and use it to set up, verify and clean up test data.

Next up is Lesson 52: ES Modules vs CommonJS, coming soon. See the course syllabus for what is already available. This completes Module 10 and the Intermediate level. Module 11 starts the Advanced level with modules, npm and Node.js.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in