Mastering Fetch API: How to GET and POST JSON in JavaScript

This guide explains how to use the JavaScript Fetch API to retrieve and send JSON data, covering basic GET requests, parsing responses, configuring request options, handling POST submissions with appropriate headers, and using polyfills for unsupported browsers.

JavaScript
JavaScript
JavaScript
Mastering Fetch API: How to GET and POST JSON in JavaScript

JSON is a simple structured data format. Example object:

{
  "name": "公众号",
  "id": "FedJavaScript",
  "isVillain": true,
  "friends": []
}

The article introduces how to use the Fetch API to get and post JSON data.

1. Calling fetch()

Fetch API provides a JavaScript interface to make HTTP requests, replacing XMLHttpRequest and supporting features such as CORS.

fetch('https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzAwNjI5MTYyMw==')

An optional second argument configures the request, for example:

{
  method: 'POST',
  body: JSON.stringify(data),
  headers: {
    'content-type': 'application/json'
  }
}

2. GET JSON

Example of fetching a list of names from /api/names and parsing the JSON response.

async function loadNames() {
  const response = await fetch('/api/names');
  const names = await response.json();
  console.log(names); // logs [{ name: 'Joker'}, { name: 'Batman' }]
}

loadNames();

By default fetch() performs a GET request, but the method can be specified explicitly.

const response = await fetch('/api/names', {
  method: 'GET'
});

To request JSON specifically, set the Accept header.

const response = await fetch('/api/names', {
  headers: {
    'Accept': 'application/json'
  }
});

3. POST JSON

Sending JSON data with a POST request.

async function postName() {
  const object = { name: 'James Gordon' };
  const response = await fetch('/api/names', {
    method: 'POST',
    body: JSON.stringify(object)
  });
  const responseText = await response.text();
  console.log(responseText); // logs 'OK'
}

postName();

This pattern also works for PUT or PATCH requests.

3.1 Explicit POST JSON

Include the Content-Type header to indicate a JSON payload.

const object = { name: 'James Gordon' };
const response = await fetch('/api/names', {
  method: 'POST',
  body: JSON.stringify(object),
  headers: {
    'Content-Type': 'application/json'
  }
});

4. Conclusion

For browsers that do not support Fetch, a polyfill can be used.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendJSONfetchAPI
JavaScript
Written by

JavaScript

Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.