Antonello Zanini
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # How To Cancel Requests in Axios Axios is one of the most popular libraries for making HTTP requests in JavaScript. One of the many great features Axios supports is request cancellation. This allows you to abort a pending HTTP request to save resources when you are no longer interested in its response. In this article, you will learn everything you need to know to become an expert when it comes to canceling requests in JavaScript. Specifically, you will see what HTTP request cancellation is, what it involves, and how to use it in Axios. Let’s dig into how to cancel HTTP requests in Axios! ## What Is HTTP Request Cancellation? HTTP request cancellation is the process of aborting a pending HTTP request before it has been completed or responded to by the server. When an HTTP request is canceled promptly, the memory and network resources allocated for it are immediately released. Canceling HTTP requests is useful whenever the user or application no longer needs the result of the request. Specifically, let’s take a look at three common examples of HTTP request cancellation: - **Search operations**: When there is search `<input>`, the page might perform an AJAX every time the user types a new character. Since the user is likely to change their query before the request completes, you should use cancellation to prevent unnecessary network traffic. - **Video streaming**: When a user is streaming a video, the webpage keeps making new HTTP requests to download the next segments of the video. If the user pauses or skips to a different part of the video, you can adopt cancellation to abort the pending requests and save network bandwidth. - **Upload/download**: When uploading/downloading a file, users may change their mind during the process. This is why you should give them the ability to abort the request. One of the best ways to implement that feature is through HTTP request cancellation. A similar approach to request cancellation is [debouncing](https://blog.openreplay.com/forever-functional-debouncing-and-throttling/). This involves delaying the new request until a certain amount of time has elapsed since the last one. Just like request cancellation, debouncing allows you to reduce unnecessary network traffic. At the same time, HTTP request cancellation is more immediate and can free up resources more quickly. Consider the example below. A user is scrolling through a list of products on a web page. The web application makes a request to fetch more products as the user reaches the bottom of the list. Now, suppose the user starts scrolling down quickly. With debouncing, there may be a delay before new products are fetched. Instead, request cancellation can immediately abort unnecessary requests and allows the page to retrieve new content immediately. ## What Happens When You Cancel an HTTP Request? When an HTTP request is aborted, what happens depends on when the cancellation occurs. Let’s consider the three possible scenarios: 1. **Before the request is sent**: If the cancellation occurs before the request is sent, the HTTP request is immediately discarded and no further action is taken. 2. **During the request transmission**: If the cancellation occurs during the transmission of the request, the HTTP request is aborted and no further data is sent to the server. The server may still receive and process the data it received before the cancellation, but the client will not wait for any response from the server. 3. **After the request has been sent**: If the cancellation occurs after the request is sent but before a response is received, the client will stop waiting for a response to that request. The server will process the HTTP request and send a response, but the client will not expect a response from it. So, the client is allowed to move on to new requests. As you can see, canceling an HTTP request as early as possible is essential to save resources, both on the client and the server. In particular, since the server may still process a request if canceled too late, you should use HTTP request cancellation only on [idempotent](https://en.wikipedia.org/wiki/Idempotence) APIs. If you are not familiar with this concept, an operation is idempotent when it can be repeated any number of times. The result of the operation will always be the same, as if it were applied only once. Thus, you should consider request cancellation only on `GET` requests, which are idempotent by nature. It is time to learn how to cancel HTTP requests in Axios! ## Cancelling HTTP Requests in Axios Axios is a popular HTTP client for JavaScript and Node.js. At the time of writing, Axios supports [two ways to cancel HTTP requests](https://axios-http.com/docs/cancellation): 1. With `CancelToken`: Deprecated in Axios since `v0.22.0`. 2. With `AbortController`: Introduced in Axios `v0.22.0`. Let’s now dig into these two approaches. ### Cancellation With `CancelToken` This approach was deprecated with Axios `v0.22.0` in October 2021, and you should no longer use it. Yet, considering how popular Axios is, some legacy apps may still rely on an older version. So, it is still worth mentioning it. You can cancel an HTTP request in Axios with `CancelToken` as in the example below: ```javascript import axios from "axios" // get the CancelToken object from axios const CancelToken = axios.CancelToken // create a cancel token instance const cancelTokenSource = CancelToken.source() // ... // perform the HTTP GET request you want to cancel axios.get('https://your-server.com/products', { // specify the cancelToken to use // for cancelling the request cancelToken: cancelTokenSource.token }).catch(function (e) { // if the reason behind the failure // is a cancellation if (axios.isCancel(e)) { console.error(e.message); } else { // handle HTTP error... } }) // ... // cancel all the HTTP requests with the same // cancelToken generated with cancelTokenSource.source() cancelTokenSource.cancel('Operation canceled') ``` The snippets above creates a cancel token instance called `cancelTokenSource` using the `CancelToken.source()` factory. Note that the value of the Axios cancel token associated with that instance is stored in `cancelTokenSource.token`. Pass this value to the `cancelToken` Axios config in all the requests you want to cancel together. Now, when you call `cancelTokenSource.cancel()`, all pending HTTP requests involving that `cancelToken` will be canceled. Congrats! You know now how to cancel HTTP requests with `CancelToken` in Axios. ### Cancellation With `AbortController` With version `v0.22.0`, Axios decided to embrace a more standard approach to HTTP cancellation. Specifically, it deprecated `CancelToken` and added support for `AbortController`. Note that canceling HTTP requests through `AbortController` is supported by all browsers and also by other HTTP clients, such as [Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) or [`node-fetch`](https://www.npmjs.com/package/node-fetch). [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) is a native JavaScript controller object that enables you to abort web requests when desired. Specifically, `AbortController` contains an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) object instance in the read-only [`signal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/signal) property. This allows you to communicate with a DOM or HTTP request and abort it when the [`abort()`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort) method is called. When a request gets canceled, a JavaScript `AbortError` is raised. This will be wrapped by Axios in a `CanceledError`. Use `AbortController` to cancel a request in Axios as in the example below: ```javascript import axios from "axios" // initialize an AbortController instance const abortController = new AbortController() // ... // perform the HTTP GET request you want to cancel axios.get('https://your-server.com/products', { // specify the AbortController signal to use // for cancelling the request signal: abortController.signal }).catch(function (e) { // if the reason behind the failure // is a cancellation if (axios.isCancel(e)) { console.error('Operation canceled'); } else { // handle HTTP error... } }) // ... // cancel all the HTTP requests with the same // signal read from abortController.signal abortController.abort() ``` Here, an `AbortController` instance gets initialized. Then, its `signal` property is passed to the Axios `signal` config in a cancellable HTTP GET request. Now, when calling the `abort()` method on the controller, all pending HTTP requests involving that `signal` will be canceled. Et voilà! You can now cancel HTTP requests using `AbortController` in Axios. ## HTTP Request Cancellation in Action Let’s see what happens in the developer tools of your browser when an HTTP request gets canceled. In the “Network” section of your browser’s dev tools, you will see something like: ![Two canceled requests](https://i.imgur.com/AdZFT1t.png) Note that “Status” is “(canceled),” which specifies that the HTTP request has been canceled. Then, in the console, you will see some “Operation canceled” errors logged by the `console.error()` instruction: ![The errors produced in the console by the canceled requests](https://i.imgur.com/mEQrdN8.png) Great! This is how you can monitor canceled requests in the developer tools of your browser. ## Conclusion This tutorial is over! You now know what HTTP request cancellation is, how it works, and how to implement it in Axios. Also, you saw how the browser behaves when an HTTP request is canceled by your JavaScript application. As learned here, canceling HTTP requests is easy. In this article, you saw everything you need to know to get started with request cancellation with Axios in both the back-end and front-end.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully