A web page often needs to load data from a server while it is open: search results, new comments, updated prices. In JavaScript, the modern tool for that is fetch(). This guide shows you how to request JSON data, check properly whether the request worked, send data to a server, and avoid the mistakes that trip up most beginners.

What fetch() does

MDN Web Docs’ guide Using the Fetch API describes the Fetch application programming interface (API) as a JavaScript interface for making Hypertext Transfer Protocol (HTTP) requests and processing the responses. It is the modern, promise-based replacement for the older XMLHttpRequest, and fetch() is available as a global function in browser windows and workers.

You pass it a uniform resource locator (URL), the address to fetch, and optionally an object of settings. It returns a promise that is fulfilled with a Response object as soon as the status and headers arrive, possibly before the body has finished downloading. You then read the body with a method such as json() or text(). These methods are asynchronous too.

Node.js also has fetch() built in. Its documentation on global objects says it has not needed a command-line flag since version 18 and has not been experimental since version 21. The outputs below come from running each example in Node.js 24.

Step 1: Request JSON data

This function asks for a small JSON (JavaScript Object Notation) file, the same address the Node.js documentation uses in its own fetch() example, and prints the names of its top-level keys:

async function getData(url) {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Response status: ${response.status}`);
    }
    const data = await response.json();
    console.log(Object.keys(data));
  } catch (error) {
    console.error(error.message);
  }
}

getData("https://nodejs.org/api/documentation.json");

Output:

[ 'type', 'source', 'introduced_in', 'miscs' ]

Each await pauses the function until a promise settles: first the response, then the parsed body. The try...catch block catches anything that goes wrong along the way.

Step 2: Always check response.ok

This step is easy to miss. The MDN reference for fetch() explains that the promise rejects only when the request itself fails, for example because of a badly formed URL or a network error. It does not reject when the server answers with an error status such as 404 or 504. Instead you check response.ok, which MDN’s Response.ok page defines as true when the status is in the range 200 to 299.

Call the same function with an address that does not exist:

getData("https://example.org/products.json");

Output:

Response status: 404

Without the ok check, the code would go on and try to read an error page as JSON.

Step 3: Send data with POST

By default fetch() makes a GET request. To send data, set the method, add a Content-Type header to tell the server what format the body is in, and put the data in body. GET requests cannot have a body.

async function sendName() {
  const response = await fetch("https://example.org/post", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ username: "example" }),
  });
  console.log(response.status, response.ok);
}

sendName();

Output:

405 false

The placeholder address answered with status 405, so ok is false. Sent to a real API that accepts the data, the same code would get a status in the 200 range. Either way, you check ok before trusting the result.

Common mistakes

  • Forgetting await. Without it you get the promise, not the response:
    const response = fetch("https://nodejs.org/api/documentation.json");
    console.log(response);

    This prints Promise { <pending> }.

  • Assuming errors reject. A 404 or 504 response still fulfills the promise. Check response.ok or response.status.
  • Calling json() on something that is not JSON. MDN notes that the body methods throw if the content is in the wrong format. Reading the HTML 404 page above with json() fails with a SyntaxError. You can check the Content-Type response header first.
  • Reading the body twice. A body is a stream and can be read only once. In Node.js, calling text() and then json() on the same response fails with TypeError: Body is unusable: Body has already been read. If you need two copies, call response.clone() before reading.
  • Blaming fetch for CORS errors. In the browser, cross-origin requests use Cross-Origin Resource Sharing (CORS). Unless the other server sends the right Access-Control-Allow-Origin header, the browser will not share the response with your code. The fix belongs on the server.
  • Expecting cookies on cross-origin requests. By default, credentials such as cookies are sent only to the same origin. The credentials option changes that, and the server must agree.

The pattern to remember is short: await fetch(), check response.ok, then await the body method you need, all inside try...catch. Add method, headers and body when you send data. With that in place, you can load and send data from both the browser and Node.js.