Reading history

JavaScript Fetch API: GET and POST JSON Requests

5 min read 1 views

Learn the JavaScript Fetch API: GET requests, reading JSON, checking response.ok, POST requests with a JSON body, error handling and CORS.

Most web apps load data from a server: weather, product lists, search results, comments. The Fetch API is JavaScript’s built-in way to send these HTTP requests. You call fetch() with a URL, it returns a promise, and you read the reply, usually as JSON. The same function also sends data to a server, for example when a form is submitted.

In this lesson you will learn

  • Making a GET request and reading JSON
  • Checking response.ok and status codes
  • Sending data with a POST request
  • Handling network errors
  • What CORS errors mean

The Basic Pattern

async function loadPosts() {
  const response = await fetch("https://api.example.com/posts");
  if (!response.ok) {
    throw new Error(`Server replied ${response.status}`);
  }
  const posts = await response.json();
  console.log(posts.length, "posts loaded");
}
  • fetch(url) sends a GET request and resolves with a Response object as soon as the server’s headers arrive.
  • response.json() reads the body and parses it, which is a second asynchronous step, so it needs its own await. Use response.text() for plain text.
  • Important: fetch only rejects when the request cannot be made at all, for example when the user is offline. A 404 or 500 reply still resolves, so always check response.ok (true for status 200–299).

GET and POST: A Complete Runnable Example

So that you can see real output, this example starts a tiny local server with Node.js and then uses fetch against it. Only the second half is what you would write in a browser app.

import http from "node:http";

// A tiny local server so this example runs without the internet
const products = [
  { id: 1, name: "Notebook", price: 80 },
  { id: 2, name: "Pen", price: 20 },
];
const server = http.createServer((req, res) => {
  if (req.method === "GET" && req.url === "/api/products") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(products));
  } else if (req.method === "POST" && req.url === "/api/products") {
    let body = "";
    req.on("data", (chunk) => (body += chunk));
    req.on("end", () => {
      const item = { id: products.length + 1, ...JSON.parse(body) };
      products.push(item);
      res.writeHead(201, { "Content-Type": "application/json" });
      res.end(JSON.stringify(item));
    });
  } else {
    res.writeHead(404);
    res.end();
  }
});
await new Promise((ok) => server.listen(0, ok));
const base = `http://localhost:${server.address().port}`;

// ---- The client code: this is how you use fetch ----
async function getProducts() {
  const response = await fetch(`${base}/api/products`);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}

async function addProduct(product) {
  const response = await fetch(`${base}/api/products`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(product),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}

try {
  console.log("GET:", await getProducts());
  console.log("POST:", await addProduct({ name: "Ruler", price: 35 }));
  console.log("Now", (await getProducts()).length, "products");

  const missing = await fetch(`${base}/api/nothing`);
  console.log("Missing page:", missing.status, missing.ok);
} catch (err) {
  console.log("Request failed:", err.message);
} finally {
  server.close();
}

Output

GET: [
  { id: 1, name: 'Notebook', price: 80 },
  { id: 2, name: 'Pen', price: 20 }
]
POST: { id: 3, name: 'Ruler', price: 35 }
Now 3 products
Missing page: 404 false
  • For a POST request, pass an options object: method, headers and a body. Objects must be turned into text with JSON.stringify(), and the Content-Type header tells the server the body is JSON.
  • The server replies with status 201 Created and the new item, which now has an id.
  • The request for a missing path does not throw; it resolves with status 404 and ok set to false.
  • One try...catch handles both network failures and the errors thrown for bad statuses.

Showing Fetched Data on a Page

const list = document.querySelector("#products");
const status = document.querySelector("#status");

async function showProducts() {
  status.textContent = "Loading...";
  try {
    const response = await fetch("/api/products");
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const products = await response.json();
    list.replaceChildren(
      ...products.map((p) => {
        const li = document.createElement("li");
        li.textContent = `${p.name}: ${p.price} taka`;
        return li;
      })
    );
    status.textContent = "";
  } catch (err) {
    status.textContent = "Could not load products. Please try again.";
  }
}
showProducts();

Show a loading message while waiting and a friendly message on failure. Use textContent for data from a server so that it can never inject HTML into your page. See the DOM lesson for more on building elements.

CORS: Why Some Requests Are Blocked

Browsers only let a page read responses from another domain if that server allows it with CORS (Cross-Origin Resource Sharing) headers. If it does not, you will see a CORS error in the console even though the URL works when opened directly. This is a server setting: the API owner must allow your site, or you call the API from your own server instead. Code running in Node.js is not affected.

Common Mistakes

  1. Not checking response.ok, then trying to parse an error page as JSON.
  2. Forgetting the second await on response.json().
  3. Sending an object as the body without JSON.stringify(); it arrives as "[object Object]".
  4. Putting secret API keys in browser code, where any visitor can read them. Keep secrets on a server.

Practice Exercises

Exercise 1. Write getJSON(url) that returns parsed JSON and throws on a bad status.

Show answer
async function getJSON(url) {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP ${response.status} for ${url}`);
  return response.json();
}

Exercise 2. Load two URLs at the same time and wait for both.

Show answer
const [users, posts] = await Promise.all([
  getJSON("/api/users"),
  getJSON("/api/posts"),
]);

Frequently Asked Questions

What is the difference between fetch and XMLHttpRequest?

Both send HTTP requests. XMLHttpRequest is the older, event-based API; fetch is newer, promise-based and simpler, and is what modern code uses.

Can I cancel a fetch request?

Yes. Create an AbortController, pass { signal: controller.signal } to fetch, and call controller.abort(). This is useful for search boxes and timeouts.

Summary

  • await fetch(url) gives a Response; await response.json() gives the data.
  • Check response.ok, because HTTP errors do not reject.
  • POST with method, a JSON Content-Type header and a stringified body.
  • CORS errors are controlled by the server you are calling.

Next: localStorage and sessionStorage.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *