简体   繁体   中英

Check HTTP status code in the Axios promise catch block VueJs

New to VueJS. I have the following code that retrieves data from the Controller using axios:

SubmitForm: function () {
    axios({
      method: 'post',
      url: '/Home/SubmitedForm',
      data: { "Fields": this.$data }
    }).then(res => {
      alert('Successfully submitted the form ');
      window.close();
      }).catch(err => {
        if (err.response.status == 409) {
          alert(`Already exists. See details: ${err}`)
        }
        else {
          alert(`There was an error submitting your form. See details: ${err}`)
        }

    });

When the Controller method SubmittedForm returns 409, I want to throw a specific alert else just throw a generic alert. Based on this page:https://gist.github.com/fgilio/230ccd514e9381fafa51608fcf137253 I wrote the above code. However, even thought the http status returned is 409, it still show the generic alert. I'm pretty sure I'm missing some understanding here. Can someone please help me find out what am I doing wrong here? Works as expected on localhost but after publishing on azurewebsites it again displays the generic error.

Maybe your API endpoint brakes CORS policy, you can't read status of such error then (despite the fact that it is visible in Networks tab in dev tools).

You can install a browser extension like "CORS everywhere" to test if it works then, but any call to API blocked by CORS will show a warning/error in the browser's console by default.

Probably because err.response.status is a string and you are comparing to number

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM