Comparing HTTP Request Mechanisms in Browser and Node.js Environments

Browser-based HTTP requests execute within the client-side execution context, while Node.js requests operate in a server-side runtime environment.

Browser-Side Request APIs: Fetch and XMLHttpRequest

Fetch API

The Fetch API is a promise-based interface for initiating network requests in modern browsers.

async function makeApiCall(url, payload) {
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(payload)
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    console.log('Success:', result);
    return result;
  } catch (err) {
    console.error('Request failed:', err);
  }
}

XMLHttpRequest

XMLHttpRequest offers granular control over request lifecycle, including upload/download tracking and manual abort handling—features not natively available in Fetch.

function sendWithXhr(endpoint, payload) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', endpoint, true);
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.upload.onprogress = (e) => {
      if (e.lengthComputable) {
        const progress = Math.round((e.loaded / e.total) * 100);
        console.log(`Upload: ${progress}%`);
      }
    };

    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve(JSON.parse(xhr.responseText));
      } else {
        reject(new Error(`Request failed: ${xhr.status}`));
      }
    };

    xhr.onerror = () => reject(new Error('Network error'));
    xhr.send(JSON.stringify(payload));
  });
}

Node.js Request Handilng Using Built-in Modules

Node.js provides low-level http and https modules to both initiating outbound requests and hosting servers.

Making an Outbound HTTP Request

const http = require('http');

function httpRequest(options, callback) {
  const req = http.request(options, (res) => {
    let buffer = '';

    res.on('data', (chunk) => {
      buffer += chunk;
    });

    res.on('end', () => {
      try {
        callback(null, JSON.parse(buffer));
      } catch (e) {
        callback(new Error('Invalid JSON response'), null);
      }
    });
  });

  req.on('error', (err) => callback(err, null));
  req.end();
}

// Usage
httpRequest(
  {
    hostname: 'jsonplaceholder.typicode.com',
    path: '/posts/1',
    method: 'GET'
  },
  (err, data) => {
    if (err) console.error(err);
    else console.log(data);
  }
);

Creating a Minimal HTTP Server

const http = require('http');

const handler = (req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ message: 'Server active', timestamp: Date.now() }));
};

const server = http.createServer(handler);
server.listen(3000, 'localhost', () => {
  console.log('Listening on http://localhost:3000');
});

Tags: javascript nodejs browser-api http-client fetch-api

Posted on Sat, 08 Aug 2026 16:38:09 +0000 by kubis