Managing the status (e.g. 503) for Axios OPTIONS response

Note: mentions that there may be no need to worry as the issue might not occur on an actual device.


In my VueJS hybrid (Cordova) app, I am utilizing Axios to make API calls.

Axios correctly initiates a 'preflight' OPTIONS request before my GET/POST requests. However, if the API responds with a 503 at that stage, my error handling code does not trigger.

HTTP.post(url, data, {headers: {Authorization: 'Bearer ' + token.getAccessToken()}})
  .then(response => response)
  .catch(error => {
    // This section is never reached
  });

How can I capture and handle this error status?


Edit: Chrome dev tools screenshot provided below:

https://i.sstatic.net/aknAx.png

Answer №1

After thorough investigation, I successfully replicated the issue and implemented a straightforward solution outlined below:

axios.interceptors.response.use(null, (error) => {
    return Promise.reject(error);
});

My testing revealed that I could accurately capture errors and responses in various scenarios.

Answer №2

When Axios encounters a Network Error, the error message can be quite vague. To provide more detail when rethrowing the error, consider using the following approach to specify which request triggered the error and what specifically went wrong:

instance.interceptors.response.use(null, error => {
  if (error && error.message === 'Network Error') {
    throw new Error(`Possible CORS preflight error on network at ${error.config.url}`);
  }
  throw error;
});

Answer №3

If you're curious about the type of HTTP status response Axios interceptor provides, check out this example:

    axios.interceptors.response.use(function (res) {
        return res;
      },
      (err) => {
        if(err.response.status == 403 || err.response.status == 503) {
            // Handle different error types
            obj[err.response.status] ? obj[err.response.status]() : obj["default"]();
        }
        return Promise.reject(err);
      });

Create a mapping with status callbacks for various behaviors.

const obj = {
    503 : () => console.log("Forbidden"),
    417 : () => console.log("I'm a teapot"),
    'default': () => console.log("Not handled")
}

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

Is there a feature in Vue.js similar to AngularJS' `ng-repeat-start` directive?

After going through vue.js documentation, I couldn't find any reference to a feature similar to ng-repeat-start / ng-repeat-end Is there a way to achieve something like this? <table> <tr class="weather_warning top" ng-repeat-start="warni ...

JavaScript syntax issue: Required formal parameter not found

Can someone help me understand why this error message is showing up in the console for the code provided? I've followed the link indicated as the issue and it points to this specific line: " $('tr').each(function() { ". (I may have included ...

execute the function whenever the variable undergoes a change

<script> function updateVariable(value){ document.getElementById("demo").innerHTML=value; } </script> Script to update variable on click <?php $numbers=array(0,1,2,3,4,5); $count=sizeof($numbers); echo'<div class="navbox"> ...

The error message "TypeError: undefined is not a function when trying to access a resource

I searched online before asking here, but couldn't find a solution. I'm attempting to call a REST service using ngResource, but my app UI isn't launching due to an error: 05-13 02:16:08.011 2402-2402/com.app.mvalt I/chromium: [INFO:CONSOLE ...

How about making an Ajax request for each item in the array?

I have a task to perform Ajax calls for each item in an array and then trigger another function once all the calls are completed. Adding complexity, I am incorporating Papa Parse into making the Ajax call. This is the code snippet: getCsvData: function( ...

Tips for successfully passing a JavaScript variable and storing it in a Rails database

I'm a beginner in Rails and I'm attempting to store a javascript variable from the view to the Rails Controller, which is then saved to a Model (database). The user participates in a quiz or survey and is then redirected to a results page. On thi ...

Using Jquery to select a specific id for an input element that is a checkbox

I've been working on a snippet of jQuery code that I'd like to tailor to be more specific for one of two different input elements on my HTML page. <script> // ensure only one box is checked at a time $(document).ready(function() { ...

What is the best way to link a file to index.html using feathers.js?

I am currently learning feathers and encountering a problem. I am attempting to include files similar to PHP's switch function. For instance: /src/middleware/index.js 'use strict'; const handler = require('feathers-errors/handler&ap ...

Having an issue with my code in angular 12 where I am unable to successfully call an API to retrieve a token, and then pass that token to another API for further processing

Here is the code snippet containing two methods: getToken and validateuser. I am fetching the token from getToken and passing it as a parameter to validateuser. However, before retrieving the token, my second API call is being executed. ...

Transmitting an Array Using an Ajax Call

Is there anyone knowledgeable in Ajax here? I'm struggling with sending a javascript array in an ajax request. Can someone provide me with an example of how the ajax request should be formatted? My goal is to gather all the javascript data, package it ...

Exploring the Capabilities of Drag-and-Drop Functionality in jsTree and DataTables

Is it possible to copy nodes from a jsTree that I've dragged to a cell in a DataTable? I'm struggling with getting this functionality to work. Any suggestions on how to achieve this? I am not seeing any alerts appear. This is the HTML code: &l ...

Loop through options in Vue.js and set a specific option as selected

When iterating through a list of objects, I am struggling to set the status of each object as selected by default. <template> <table class="table is-striped"> <thead> <tr> <th> ...

Confirmed the validation of an input that falls outside the parameters of the ReactiveForms model

Check out this StackBlitz example In my Angular application, I am utilizing a Reactive form with 3 inputs, each having its own validation. Additionally, there is an input that exists outside of the form within its own component, also with its own reactive ...

The app running in node.js encountered a "connection timed out" error

Whenever I try to run my Node.js app by executing "node app.js" and setting NODE_ENV to production, it doesn't seem to be recognized as production. Instead, I encounter a connection timeout error when trying to run the app. My goal is to establish a c ...

Tips for resolving table header issues and enabling vertical movement of data while simultaneously allowing both the header and data to move vertically

I need assistance with a challenge I am facing. I have created a table using HTML tags, and now I want to add a vertical scrollbar to the browser without affecting the table's header. The data in the table should move when the vertical scrollbar is us ...

Extract a specific pattern from a string using Javascript

Currently, I am attempting to extract a specific string from a tag in javascript using the following code: document.querySelector('.title h2').textContent However, when I execute this code, I am getting a result that includes unnecessary double ...

Is there a workaround for unresolved symlink requirements when using npm link?

Creating an NPM package often involves using the following: npm link This allows for making modifications to a package called <myPackage> during development without constantly having to publish and unpublish! Developers can make changes locally and ...

Discovering the process of extracting a date from the Date Picker component and displaying it in a table using Material-UI in ReactJS

I am using the Date Picker component from Material-UI for React JS to display selected dates in a table. However, I am encountering an error when trying to show the date object in a table row. Can anyone provide guidance on how to achieve this? import ...

Vue 3 - Child Component Script Not Updating with Reactive Prop Changes

I am facing an issue where I am trying to pass a reactive data as a prop to a child component in Vue 3. The data updates correctly in the child component's template, but it does not reflect in the child component's script. In the parent component ...

Establish remote functionality for a JSON AJAX PHP form

Recently, I encountered an issue with my Javascript code that interprets JSON from PHP. Surprisingly, it works perfectly fine on my local server, but when I attempt to transfer the script to a different server, it fails to function. To address this, I have ...