0

I have a Vue application where I make a POST request to my backend. I am now trying to call a validation method after the response from my backend returned back an error to my frontend. But for some reason my code is not executed:

UPDATED QUESTION CODE:

     validateFormInput(){
      this.$refs.form.validate()
    },
  saveSelectionVoter() {
    var pageURL = window.location.href;
    var lastURLSegment = pageURL.substr(pageURL.lastIndexOf('/') + 1);
    this.votersSelectArray.voterAvailableTimes = [...this.votersSelectArray.voterAvailableTimes, ...this.selected]

    console.log(JSON.stringify( this.votersSelectArray))

    axios.post("http://localhost:8080/api/votercontroller/",
        this.votersSelectArray,
        {
          params: {
            meetingName: lastURLSegment,
          }
        },
    ).then(function(response){
    })

        .catch(function (error){
          this.validateFormInput()
    console.log(error)
    })
    this.selected = []


  },

This causes a new error:

TypeError: Cannot read property 'validateFormInput' of undefined
natyus
  • 577
  • 1
  • 4
  • 19
  • response errors (> 400 status code) will be in the `catch` block because it failed from the server side (422 is validation error). – Sysix Jul 02 '21 at 20:53
  • But my response.data is send to my frontend? I can see it inside the console under networks -> preview can I not use it somehow? Or what would be your suggestion – natyus Jul 02 '21 at 20:55
  • Does this answer your question? [Axios handling errors](https://stackoverflow.com/questions/49967779/axios-handling-errors) – Sysix Jul 02 '21 at 20:56
  • I updated my code to catch the error which is catched, but if I try to validate now my code I am getting this error: TypeError: Cannot read property 'validateFormInput' of undefined – natyus Jul 03 '21 at 08:26

2 Answers2

0

always have a catch to see the error return axios return you a promise so it captures the error if there is any

axios.post('url')
  .then((res) => {
   // do somthing 
  }).catch(err){
   console.log(err)
  }
khazim
  • 11
  • 4
0

You can either use the callback method to catch the response/error or use the Promise way, which is my favorite because of scope and readability.

You start by declaring your function with async

async saveSelectionVoter() {

Then you use a try/catch block to handle the response/error:

try{
const response = await axios.post(url, params)
 // handle response here
} catch (error) {
// handle error here
}
  • I updated my code thanks for the answer but I had seen it too late, maybe you can take a look at my new problem with the updated question – natyus Jul 03 '21 at 08:26