Inspect the HTTP response status code within the Axios promise catch block in VueJs

Recently started using VueJS. I have created the code below to fetch data from the Controller with axios:

SubmitForm: function () {
    axios({
      method: 'post',
      url: '/Home/SubmitedForm',
      data: { "Fields": this.$data }
    }).then(res => {
      alert('Form submitted successfully ');
      window.close();
      }).catch(err => {
        if (err.response.status == 409) {
          alert(`Data already exists. Details: ${err}`)
        }
        else {
          alert(`There was an issue submitting your form. Details: ${err}`)
        }

    });

When the Controller's SubmittedForm method returns a status of 409, I want to display a specific alert, otherwise, a generic one. However, despite getting a 409 status, it only displays the generic alert message instead of the expected specific one, as per the reference page provided in the code. I suspect there might be something I'm missing or misunderstanding. Would appreciate any help in identifying what I could be doing wrong. The functionality works fine on localhost but after deploying to azurewebsites, it reverts back to showing the generic error message.

Answer №1

It's possible that your API endpoint is violating the CORS policy, preventing you from accessing error status information (even though it can be seen in the Networks tab of the developer tools).

To troubleshoot this issue, consider installing a browser extension such as "CORS everywhere" to see if it resolves the problem. Keep in mind that any attempt to access an API blocked by CORS will result in a warning or error message appearing in the browser console.

Answer №2

It's likely that err.response.status is being stored as a string, causing the comparison to fail since you are trying to compare it to a number.

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

What is the best way to add animation to my `<div>` elements when my website is first loaded?

I am looking for a way to enhance the appearance of my <div> contents when my website loads. They should gradually appear one after the other as the website loads. Additionally, the background image should load slowly due to being filtered by the wea ...

Is there only a single particle in Three.js?

I am trying to add a single particle to my scene and have the ability to move it around. However, my attempts to do so without using a Particle System have been unsuccessful. Whenever I try to render the particle as a mesh, nothing appears on the screen. I ...

What is the best way to iterate through the response text in a JSON file?

In a JSON file, I have objects structured like this: { "status": "ok", "feed": { }, "items": [ { "title": "", "author": "" }, { "title": "", "author": "" }, ...

Adjusting the transparency of a Div element as you scroll

Before you get mad, let me clarify that I have combed through countless resources and forums, but I still can't seem to crack this code. I whipped up a basic website to grasp the concept before applying it to a more intricate project. I've experi ...

Choosing values from a variety of select option boxes using jQuery

I'm experiencing an issue with selecting values in a multiple select option box. Despite my efforts, I haven't been able to get all the desired items selected at once. Currently, when I run the code below, only the first option is being selected ...

Exploring Django with Selenium: How to Extract Page Content Using find_element

I have been attempting to extract the text 'Incorrect Credentials' using selenium. Here is what I have experimented with... message_text = self.driver.find_element(By.XPATH, '//*[@id="toast-container"]/div/div[1][@class="ng-binding toast-t ...

Omit a Mongoose field in a query by utilizing the assignment operator

Despite recognizing that this question has been posed previously, I have not been able to find a solution suitable for my specific scenario. Many websites recommend using .select('-queryData'), but I am unsure how to implement it in my case. My ...

How can you ensure your presence is known when a specific directive attribute has been removed from the DOM?

I am searching for a solution to catch the attention if an element is added and then removed from the DOM. When the element is removed, I want to retrieve the ng-model value of that specific element. For instance: <div notify-when-removed ng-model="s ...

JavaScript code that compares dates in an array, then calculates the total price for each month and year

I have a JSON file containing various transactions with both a date and a price attribute. My goal is to compare the dates, identify transactions that occur in the same month and year, and calculate the total price of those transactions. JSON: transactio ...

Steps to deactivate a div in React after a single click

When you click the "show" button for the first time, it displays "hello world" correctly. However, if you click on show again, it should not work. How can I make it so that after one click, it does not hide hello world if you click again? I've tried u ...

Implementing JSON in a Rails 4.2 Application

Recently, I developed a layout designer using Canvas that is configured via a JSON file specifying background, fonts, colors, and more. Now, my next challenge is integrating it into a Rails application. However, I'm finding it difficult to find releva ...

The significance of documenting and optimizing code execution

My coding practice is to always (or at least try to) add comments to my code. However, I have set up my server to delete those comments and extra white space before the final delivery. Should I omit comments from the live system's code (Javascript/php ...

Tips for effectively managing Angular JS dependencies and promoting modularity

As I embark on a new project from the ground up, my main focus is creating a responsive website optimized for mobile devices. In order to achieve this goal, I am seeking information about Angular: How does Angular manage its resources and dependencie ...

`Dynamic assortment displaying menu`

I am currently developing a compact application that requires a list of 5 items: Name Address City Country Zipcode Whenever a user clicks on any of these items, they should be redirected to another page where that specific item is highlighted. ...

Executing database queries in a synchronous manner in JavaScript

let positionConfig = require('setting'); function retrieveConfig(element) { let setting; positionConfig.find({element: element}, function (err,docs) { console.log(docs[0].current); // show the value setting = docs[0].curr ...

Detecting the rectangular boundary of rotated elements on a dynamically generated canvas or SVG using JavaScript (TypeScript)

I've been struggling with a particular issue for some time now. Currently, I'm developing a web application using TypeScript, React, and Google Maps. For the markers on the map, I aim to use custom images generated at runtime based on various pa ...

Object3D.frustumCulled property in ThreeJS helps determine if an object

In ThreeJS, Object3D objects have a built-in function to determine if they are within the camera's view - Object3D.frustumCulled. Is there a way to access and retrieve the result of the "Object3D.frustumCulled" check? ...

Troubleshooting: jQuery unable to locate element within iframe

I need help finding all elements within an iframe that contain a specific word, for example, 'stack' on this page: http://en.wikipedia.org/wiki/Stack_Overflow Here is the code I am currently using: <body> <iframe src="http://en.wik ...

What is the best way to trigger JQuery based on changes in the URL hashtag?

I recently integrated a history plugin called really simple history, and I believe it's working well. The next step is to ensure my ajax responds when the user navigates through the history (by pressing the back or forward button). My initial thought ...

Add 'http://' to hrefs that do not have a protocol specified in Angular

I've been trying to come up with a solution to automatically add "http://" to any href links that don't already have it before the link. Here is what I currently have: static correctUrls(input: string): string { // extract all hrefs from the ...