SuperAgent - Refresh the initial request with a new bearer token upon encountering unauthorized access

Issue:

I encountered a problem while attempting to resend my original request using superagent. Here is some pseudo code that I came up with:

function retryRequest({
    params
}) {
    return superagent.post(url)
    .set("Authorization", `Bearer ${process.env.initialToken}`)
    .send({data})
    .then(res => {
        if (res.unauthorized) { 
          // My goal is to make an API call, obtain a new token, and then retry the postRequest() with the updated bearer
        }
    })
    .catch(err => {
        throw err
    });
}

Inquiries:

While researching how others handle this situation, I observed that some developers tackle it in the catch block, while others address it within the response. Additionally, some incorporate the .on plugin to validate.

Upon examining the superagent documentation, I am contemplating whether I should experiment with a custom retry() function. Is there a possibility of utilizing

request.auth('my_token', { type: 'bearer' })
in a certain manner? Although seemingly straightforward, deciphering their documentation for such scenarios can be challenging. I would appreciate hearing your insights on this matter!

Answer №1

Resolution - Successfully resolved the issue by recursively calling the function with the original parameters. This approach can be applied in error handling scenarios as well.

Important to mention - The retry() API has limitations and may not function correctly for 401 errors, while using plugins might be excessive for this specific situation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting dates in JavaScript to the format (d MMMMM yyyy HH:mm am) without using moment.js

Looking to convert the date "2020-02-07T16:13:38.22" to the format "d MMMMM yyyy HH:mm a" without relying on moment.js. Here is one method being utilized: const options = { day: "numeric", month: "long", year: "numeric", } var date1 = new Date ...

Can VueJS lifecycle hooks be outsourced?

Is it possible to organize lifecycle hooks (like created / mounted) in a separate file for better simplicity and cleanliness? MyGreatView.vue import created from 'created.js' export default { created, // created() { console.log('vue Cre ...

Showing off HTML tags within react-json-tree

I have incorporated the following npm package into my project: https://www.npmjs.com/package/react-json-tree My goal is to showcase a json tree in react, but I am facing a challenge on how to include an HTML tag as a JSON value. Are there any alternative ...

What could be causing my array to update when the method is called live but not during unit tests?

One of my methods is called toggleSelect which adds and removes items from an array named selectedItems. This method functions perfectly when I test it live in the browser. However, when running unit tests, it does not seem to work as expected. Despite cal ...

Troubleshooting Angular: Unidentified property 'clear' error in testing

I've implemented a component as shown below: <select #tabSelect (change)="tabLoad($event.target.value)" class="mr-2"> <option value="tab1">First tab</option> <op ...

What is the reason behind the fact that the "transform" property of document.getElementById().style.transform="translateX()" only translates the element once?

I'm currently in the process of developing a new online game. With just a simple click of a button, my goal is to have the red square move horizontally by 50 pixels. Here's a snippet of the HTML code: <!DOCTYPE html> <html> <hea ...

Unable to detect hover (etc) events after generating div elements with innerHTML method

After using the code below to generate some divs document.getElementById('container').innerHTML += '<div class="colorBox" id="box'+i+'"></div>'; I am encountering an issue with capturing hover events: $(".colorB ...

The "tsc" command in Typescript seems to be acting up. I've exhausted all possible solutions but

Hello there, I find myself struggling to run Typescript throughout the day while utilizing Visual Studio Code. My usual method involves installing TS globally: $ npm install -g typescript But every time I try to use it, I encounter the same error: bas ...

By implementing Async.parallel, I ensure that the lifetime of my parameter does not exceed the duration of the asynchronous calls in NodeJS when working with MongoDB

After analyzing the code and its asynchronous behavior, it appears that the 'recipeData' array may not persist long enough to handle the asynchronous callbacks. To mitigate this, I created a copy of the data in a global array. However, I am encou ...

Unable to fetch Title from Strapi

I have a collection type named posts with the following values: https://i.sstatic.net/49OeV.png To access the API, I have a file in my lib folder that contains the following code: export async function getPosts() { var api_base_url = process.env.API_BASE ...

When you download a file through the unpkg CDN, the size of the npm package is

I am experiencing a discrepancy with the file size of a file in my npm package. The file is 307kb in size, but when I download it through unpkg, the same file is only 73.2Kb. I find it quite puzzling how the file can be smaller when downloaded over the net ...

Exploring innovative designs for asynchronous JavaScript programming

Imagine you have an Express app and you need to retrieve data from a database to display on the frontend. There's a function in your code that looks like this (using node-mysql for handling database queries) exports.getData = function() { ...

Error encountered when attempting to create an index in ElasticSearch due to

I am encountering an issue with the elasticsearch npm module while attempting to create an Index, resulting in a TypeError with the following message: Unable to build a path with those params. Supply at least index The code snippet I am using is as follo ...

What is the technique for incorporating FontAwesome icons onto an HTML 5 canvas?

I am encountering an issue while trying to use FontAwesome icons within my HTML 5 canvas. Here is what I have attempted: ct.fillStyle = "black"; ct.font = "20px Font Awesome"; ct.textAlign = "center"; var h = 'F1E2'; ct.fillText(String.fromCha ...

Guide on accessing js file in an Angular application

I have a component where I need to create a function that can search for a specific string value in the provided JavaScript file. How can I achieve this? The file path is '../../../assets/beacons.js' (relative to my component) and it's named ...

Automate the execution of webdriver/selenium tests when a form is submitted

I am currently faced with a challenge in setting up an application that will automate some basic predefined tests to eliminate manual testing from our workflow. The concept is to input a URL via a user-friendly form, which will then execute various tests ...

Troubleshooting: jqGrid's reload function is not functioning properly

I am encountering an issue when trying to reload the grid using trigger('reloadGrid'). I make an AJAX call to the server and the server returns the xmlstring successfully, however, the grid does not update with the new data. Below is the code sni ...

The Ajax script triggers the PHP script twice

Utilizing AJAX on my HTML page, I am able to dynamically load data from a MySQL database without reloading the page and send email notifications upon certain events. The process involves Ajax calls to script.php which then makes requests to the database an ...

Iterating through a JSON object using an API loop

Just starting out in JS and I am attempting to use a for loop to combine all the 'text' from various JSON objects into one cohesive paragraph. For example, it should read like this: "Hello, and welcome to the Minute Physics tutorial on basic Rock ...

VeeValidate fails to validate input fields in a form that is constantly changing

My goal is to create dynamic forms with validations using veeValidate in Vue.js. I am attempting to achieve this by storing an array of objects within the component's data. For instance: data(){ return{ inputs: [ { id: 1, lab ...