How to cancel an HTTP request in Node.js

Click for: original source

If you’re making an HTTP request in Node.js there’s a good chance you’ll want to cancel it if it takes too long to receive a response. Or perhaps you have a slightly more complex situation where you’re making multiple requests in parallel, and if one request fails you want to cancel all of them. By Simon Plenderleith.

const controller = new AbortController();
const signal = controller.signal;

signal.addEventListener("abort", () => {
  console.log("The abort signal was triggered");
}, { once: true });

controller.abort();

Fortunately there’s a JavaScript API which gives us a standard way to cancel asynchronous tasks such as an in-flight HTTP request: the Abort API.

The article then goes and describes:

  • The Abort API
  • Cancelling an HTTP request with an AbortSignal
  • Support for cancelling HTTP requests
  • Libraries
  • Node.js core API methods

An interesting note from author: I’m pretty sure we’re going to see a lot more of the Abort API as other libraries, as well as methods in Node.js core, add support for it. Good read!

[Read More]

Tags devops nodejs javascript web-development open-source app-development