Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For most new JavaScript code, use the built-in fetch() API. It works in modern browsers, workers, and current Node.js releases, and returns a Promise you can await. The key detail: Fetch does not reject just because a server returns an HTTP error such as 404 or 500, so check response.ok before reading the response. Use XMLHttpRequest when you need its event-based progress controls or must maintain existing code, Axios when a project benefits from a shared HTTP-client abstraction, Node’s http/https APIs for low-level server-side stream control, and EventSource for one-way live updates from a server to a browser.

1. Use Fetch for ordinary requests

The Fetch API is the modern baseline for making HTTP requests in browser and worker code. It is built into modern browsers and current Node.js releases, so a basic request needs no package installation. Fetch resolves its Promise when response headers arrive; it does not treat a non-2xx status as a network failure. Check response.ok (or response.status) explicitly.

GET JSON and handle failures

async function getProducts() {
  const response = await fetch("https://example.org/products.json");
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }
  return response.json();
}

getProducts()
  .then(products => console.log(products))
  .catch(error => console.error("Request failed:", error));

response.json() is asynchronous too, so return or await it. If the endpoint returns a different format, use the matching Response method, such as response.text() or response.blob(). A response body is consumed when read; do not try to parse the same body twice without cloning the response first.

POST JSON

async function createUser() {
  const response = await fetch("https://example.org/users", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ username: "ada" })
  });

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

  return response.json();
}

Set the method, content type, and serialized body deliberately. The example assumes the endpoint returns JSON; if it returns no content, do not call response.json().

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Browser cross-origin requests

In a browser, a request to a different origin is subject to CORS. The target server must allow the requesting origin and the requested access. Certain cross-origin requests cause the browser to send a preflight request first. The server must permit the method and headers before the browser sends the actual request.

Setting mode: "no-cors" is not a way to bypass CORS: it restricts which methods and headers can be used and gives JavaScript an opaque response whose status and body it cannot inspect. If a browser request is blocked, configure the server’s CORS policy or make the request from a server you control; changing the client to no-cors will not make the response usable.

Timeouts and cancellation

Fetch supports cancellation with an AbortSignal, which is useful when a user navigates away or an operation should not wait indefinitely. Set an appropriate timeout policy for your application and handle aborts separately from HTTP status errors: an aborted request has no completed response to inspect.

2. Use XMLHttpRequest for progress events or existing code

XMLHttpRequest (XHR) remains useful when an application relies on its event-oriented API, especially upload or download progress events and explicit response-type controls. Its usual sequence is to create an object, call open(), attach listeners, and call send().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const xhr = new XMLHttpRequest();
xhr.open("GET", "/data.json");
xhr.responseType = "json";

xhr.addEventListener("load", () => {
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log(xhr.response);
  } else {
    console.error(`HTTP ${xhr.status}`);
  }
});

xhr.addEventListener("error", () => {
  console.error("Network error");
});

xhr.addEventListener("progress", event => {
  if (event.lengthComputable) {
    console.log(`${event.loaded} of ${event.total} bytes`);
  }
});

xhr.send();

XHR’s load event means the request completed, not necessarily that the status succeeded, so inspect xhr.status. The progress event can report transferred bytes when the total is known. For upload progress, attach a progress listener to xhr.upload.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Use asynchronous requests for interactive pages. Synchronous XHR outside a Web Worker blocks the main interface while it waits and should not be used for normal page interactions. Fetch is generally simpler for new request/response code; XHR is a practical choice when progress events or existing integrations matter.

3. Use Axios when you want a client library

Axios is a Promise-based HTTP client for browsers and Node.js. Choose it when a project wants a common library abstraction across its application, rather than calling Fetch or Node’s lower-level API directly. It is an additional dependency, and its precise behavior can depend on the installed release and adapter.

Install Axios through the package manager used by your project, then import it:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import axios from "axios";

async function loadProducts() {
  try {
    const { data } = await axios.get("https://example.org/products.json");
    return data;
  } catch (error) {
    console.error("Request failed:", error);
    throw error;
  }
}

async function createUser() {
  const { data } = await axios.post("https://example.org/users", {
    username: "ada"
  });
  return data;
}

Axios exposes the parsed result as data in its response object, as shown. Handle rejected requests with try/catch and consult the installed version’s documentation for its configuration and adapter details. Do not assume a library and the browser’s built-in Fetch have identical edge-case behavior.

4. Use Node.js http or https for low-level control

Node’s built-in http and https modules provide lower-level access to requests and response streams. They are useful when you need direct control over headers, sockets, or streaming, and accept the extra callback and event handling. Use https for an HTTPS URL.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
import https from "node:https";

https.get("https://example.org/data.json", (res) => {
  let body = "";
  res.setEncoding("utf8");

  res.on("data", chunk => {
    body += chunk;
  });

  res.on("end", () => {
    if (res.statusCode < 200 || res.statusCode >= 300) {
      console.error(`HTTP ${res.statusCode}: ${body}`);
      return;
    }

    try {
      console.log(JSON.parse(body));
    } catch (error) {
      console.error("Response was not valid JSON:", error);
    }
  });
}).on("error", error => {
  console.error("Request failed:", error);
});

Unlike a high-level JSON helper, this example collects text and parses it itself. For large responses, avoid buffering the entire body into a string if streaming processing is more appropriate. Also check the HTTP status: receiving a response stream does not itself mean the operation succeeded.

5. Use EventSource for one-way live updates

EventSource keeps an HTTP connection open so a server can send a stream of server-sent events (SSE) to a browser. It is designed for one-way updates: the browser receives messages, but cannot send events back to the server over that same EventSource connection. Use Fetch, XHR, or Axios for ordinary client requests and uploads; use WebSockets when the application needs a bidirectional, long-lived channel.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const events = new EventSource("/events");

events.onmessage = event => {
  try {
    const update = JSON.parse(event.data);
    render(update);
  } catch (error) {
    console.error("Could not parse event:", error);
  }
};

events.onerror = () => {
  console.error("Event stream encountered an error");
  events.close();
};

EventSource is not a general replacement for a request/response API. The server must provide an SSE endpoint, and the browser maintains the stream while it is open. Decide how your application should respond to stream errors—such as whether to close it or allow reconnection—rather than treating it like a one-shot GET.

Which JavaScript HTTP approach should you choose?

Approach Environment and best fit Trade-off
Fetch Modern browsers, workers, and current Node.js; ordinary request/response work Check non-2xx statuses yourself; browser CORS rules still apply
XMLHttpRequest Browser code needing progress events, response-type controls, or legacy compatibility Event-based plumbing; synchronous main-thread use blocks the interface
Axios Browser and Node.js projects wanting a shared client abstraction Additional dependency; exact adapter behavior is release-sensitive
Node http/https Server-side code needing low-level stream or connection control More manual event and response handling
EventSource Browser clients receiving one-way server-sent updates over HTTP Cannot send client events back on the same channel

For a standard API call, start with Fetch unless a concrete requirement points elsewhere. Progress-oriented browser code may favor XHR; a team-standard client library may justify Axios; low-level Node stream work suits the native modules; and server-to-browser live updates call for EventSource.

Or skip the browser setup

If the HTTP task is capturing a web page as an image or PDF, ScreenshotNeo provides a screenshot API and MCP server for developers. A single GET request can return a PNG, JPEG, WebP, or PDF. See the ScreenshotNeo site and API documentation.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Save the response body as a file in application code if you need to keep the returned image. ScreenshotNeo accepts and removes cookie-consent banners, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers identify the page verdict and billing status. Its MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Sign up free for 1,000 screenshots a month with no card.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting common HTTP request problems

Fetch appears successful, but the API returned an error

A fulfilled Fetch Promise only means a response arrived. Check response.ok or the status before parsing and handle non-2xx responses explicitly.

The browser reports a CORS error

The server may not allow the page’s origin, method, or headers. Configure the server’s CORS response and preflight handling. no-cors will not expose the response to your JavaScript.

JSON parsing fails

Confirm that the endpoint actually returns JSON and that the response body has not already been consumed. Check the status and response content before assuming every response, including an empty success, can be parsed with json().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

XHR completes but the application reports the wrong result

Inspect xhr.status in the load handler. The event reports completion, not success; use error for network-level failures.

Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Node receives text that cannot be parsed

Check the response status and payload before calling JSON.parse(). The endpoint could return an error document or non-JSON content; catch parse errors as a separate failure from request errors.

An event stream stops updating

Verify that the URL points to an SSE endpoint and that the server is sending events in the format EventSource expects. Decide whether an error should close the stream, as in the example, or whether the application should let its connection behavior continue.

FAQ

Does Fetch work in Node.js?

Fetch is available in current Node.js releases as well as modern browsers and worker contexts. For older runtime targets, verify the runtime’s support or use a client compatible with that environment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is EventSource the same as WebSockets?

No. EventSource provides one-way server-to-browser updates over HTTP. WebSockets are the relevant option when both sides need to communicate over a bidirectional, long-lived connection.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.