Exercise 2: POST JSON (with headers)

Problem Statement

Create a function `postJson(url, data)` that performs POST and returns response JSON.

Sample Output:

await postJson("https://api.example.com/users", {name: "John"}) => {id: 1, name: "John"}
await postJson("https://api.example.com/login", {email: "test@test.com"}) => {token: "..."}

Solution

const postJson = async (url, data) => {
  const res = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });
  if (!res.ok) throw new Error('HTTP ' + res.status);
  return res.json();
};

Explanation

Overall Goal:

  • POST request bhejna: data server ko send karna.
  • JSON format me data send karna.

Line 1: Async function

  • const postJson = async (url, data) => {
  • url → API endpoint.
  • data → JavaScript object jo send hona hai.

Line 2-6: Fetch with options

  • const res = await fetch(url, { ... });
  • Second argument → request options object.

Line 3: HTTP method

  • method: 'POST' → POST request (data send).
  • Default method GET hai, isliye explicitly specify karna.

Line 4: Headers

  • headers: { 'Content-Type': 'application/json' }
  • Content-Type → server ko batata hai ki data JSON format me hai.
  • Server JSON parse kar sakega.

Line 5: Request body

  • body: JSON.stringify(data)
  • JSON.stringify(data) → JavaScript object ko JSON string me convert.
  • Example: {name: "John"}'{"name":"John"}'.
  • body → request me data send karta hai.

Line 7: Status check

  • if (!res.ok) throw new Error('HTTP ' + res.status);
  • Same as fetchJson: error handling.

Line 8: Parse response

  • return res.json(); → response JSON parse karke return.

Real world:

  • Contact forms: user message send karna.
  • Login: credentials submit karna.
  • Checkout: order data submit karna.