【问题标题】:How to use a conditional validation after Axios call in Vue appVue app中axios调用后如何使用条件验证
【发布时间】:2021-09-14 18:07:50
【问题描述】:

我有一个 Vue 应用程序,我在其中向我的后端发出 POST 请求。在我的后端的响应返回一个错误到我的前端后,我现在尝试调用验证方法。但由于某种原因,我的代码没有执行:

更新的问题代码:

     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 = []


  },

这会导致一个新的错误:

TypeError: Cannot read property 'validateFormInput' of undefined

【问题讨论】:

  • 响应错误(> 400 状态代码)将在 catch 块中,因为它从服务器端失败(422 是验证错误)。
  • 但是我的 response.data 被发送到我的前端?我可以在网络下的控制台内看到它-> 预览我不能以某种方式使用它吗?或者你的建议是什么
  • 这能回答你的问题吗? Axios handling errors
  • 我更新了我的代码以捕获捕获的错误,但如果我现在尝试验证我的代码,我会收到此错误:TypeError: Cannot read property 'validateFormInput' of undefined

标签: javascript vue.js axios vuetify.js


【解决方案1】:

您可以使用回调方法来捕获响应/错误,也可以使用 Promise 方式,这是我最喜欢的方式,因为它的范围和可读性。

你首先用 async 声明你的函数

async saveSelectionVoter() {

然后你使用 try/catch 块来处理响应/错误:

try{
const response = await axios.post(url, params)
 // handle response here
} catch (error) {
// handle error here
}

【讨论】:

  • 我更新了我的代码,谢谢你的回答,但我看到它为时已晚,也许你可以看看我更新后的问题的新问题
【解决方案2】:

总是有一个catch来查看错误返回 axios 向您返回一个承诺,以便在有任何错误时捕获错误

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

【讨论】:

    猜你喜欢
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 2021-08-31
    • 2018-05-20
    • 2018-02-05
    • 2011-01-20
    • 1970-01-01
    相关资源
    最近更新 更多