在 vue.js 中捕获 API 请求中的错误

abu*_*abu 1 vuejs2

我正在尝试捕捉错误

this.$http.post('http://127.0.0.1:8000/api/address/store',address_data,{headers: {'Authorization': 'Bearer ' + this.$auth.getToken()}}).then(response => {
                    if(response.status == 422) {
                        console.log('hello')
                        console.log(response)
                    }
            })
Run Code Online (Sandbox Code Playgroud)

但我不能用这种方式捕捉。谢谢。

dou*_*lea 5

看起来您正在使用 vue-resource 来发出 ajax 请求。我只使用过 axios,但查看 vue-resource 的文档看起来你的错误回调是第二个参数.then()

例子

this.$http.post('/someUrl', [body], [config]).then(successCallback, errorCallback);

在你的代码中试试这个

this.$http.post('http://127.0.0.1:8000/api/address/store',address_data,
  {headers: {'Authorization': 'Bearer ' + this.$auth.getToken()}})
  .then(response => {
    // success
  }, response => {
    //error
    if(response.status == 422) {
      console.log('hello')
      console.log(response)
    }
  })
Run Code Online (Sandbox Code Playgroud)

这是文档的链接:https : //github.com/pagekit/vue-resource