npm request cancel

How to Cancel an NPM Request?

If you want to cancel an NPM request, there are a few ways to do it. Here are some methods:

Method 1: Using the Request Aborted Event

If you are using the request module in Node.js, you can cancel a request by using the aborted event. This event is emitted when the request is aborted either by the client or the server.


const request = require('request');

const req = request('http://www.example.com');

req.on('response', (res) => {
  console.log('Response received!');
});

req.on('error', (err) => {
  console.log(err);
});

req.on('abort', () => {
  console.log('Request aborted!');
});

// cancel the request after 1 second
setTimeout(() => {
  req.abort();
}, 1000);

Method 2: Using Axios

If you are using the axios library in Node.js or in the browser, you can cancel a request by creating a CancelToken and passing it to the config object of your request.


const axios = require('axios');

const source = axios.CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).then((response) => {
  console.log(response.data);
}).catch((error) => {
  if (axios.isCancel(error)) {
    console.log('Request canceled!');
  } else {
    console.log(error);
  }
});

// cancel the request after 1 second
setTimeout(() => {
  source.cancel('Operation canceled by the user.');
}, 1000);

Method 3: Using Fetch

If you are using the fetch method in the browser, you can cancel a request by creating an AbortController and passing its signal property to the fetch method.


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

fetch('/data', { signal })
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    if (error.name === 'AbortError') {
      console.log('Request aborted!');
    } else {
      console.log(error);
    }
  });

// cancel the request after 1 second
setTimeout(() => {
  controller.abort();
}, 1000);

These are some of the ways to cancel an NPM request. Choose the method that best suits your needs.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe