Skip to main content

Command Palette

Search for a command to run...

Advanced JavaScript: Network Requests, Headers, Body & Postman

Published
2 min read

JavaScript allows you to interact with servers and APIs using network requests. Understanding this is essential for building dynamic web apps. Let’s break it down.


1. Network Requests in JavaScript

JavaScript communicates with servers via HTTP requests to fetch or send data.

a) Fetch API (Modern & Promise-based)

fetch('https://api.example.com/data')
  .then(response => response.json())  // parse JSON
  .then(data => console.log(data))
  .catch(error => console.error(error));
  • Supports GET, POST, PUT, DELETE, etc.

  • Returns a Promise.

  • Can include headers and body.

b) XMLHttpRequest (Older, Callback-based)

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = () => console.log(JSON.parse(xhr.responseText));
xhr.send();
  • Works in all browsers.

  • Verbose; mostly replaced by fetch.

c) Axios (Third-party library)

axios.get('https://api.example.com/data')
  .then(res => console.log(res.data))
  .catch(err => console.error(err));
  • Auto-parses JSON.

  • Handles timeouts, interceptors, and request cancellation.

  • Easier syntax for POST requests.


2. HTTP Methods

MethodPurpose
GETFetch data
POSTSend data
PUT / PATCHUpdate data
DELETERemove data

3. Request Headers

Headers provide metadata about the request.

Example:

fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',  
    'Authorization': 'Bearer token123'
  },
  body: JSON.stringify({ name: 'Paras', age: 20 })
});

Common Headers:

  • Content-Type: Type of data (application/json, text/plain, etc.)

  • Authorization: API token or credentials

  • Accept: Expected response format

  • Custom headers: Any server-specific info


4. Request Body

  • Used in POST, PUT, PATCH requests.

  • Can be JSON, FormData, URL-encoded, etc.

JSON Body:

fetch('/api/user', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ username: 'Paras', password: '12345' })
});

FormData (for files or forms):

const formData = new FormData();
formData.append('file', fileInput.files[0]);
fetch('/upload', { method: 'POST', body: formData });

5. Postman

A GUI tool to test APIs without writing code.

  • Set URL & HTTP method.

  • Add headers & body.

  • View responses and status codes.

  • Useful for debugging APIs before integrating with JS.

Example workflow:

  1. URL: https://api.example.com/login

  2. Method: POST

  3. Headers: Content-Type: application/json

  4. Body: { "username": "Paras", "password": "12345" }

  5. Click Send → Inspect JSON response


6. Hands-on Practice

Try the free API JSONPlaceholder:

// GET request
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(res => res.json())
  .then(console.log);

// POST request
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ title: 'Hello', body: 'JS is fun', userId: 1 })
})
.then(res => res.json())
.then(console.log);

💡 Pro Tip: Always check the network tab in DevTools to debug requests and responses. Combine it with Postman for a smoother workflow.