Axios:不会进入带有错误的catch方法

时间:2018-09-27 13:55:55

标签: javascript laravel vue.js axios

我具有编辑合同名称的功能。我使用特定ID调用axios请求到后端API。对于每种情况,我都会调用一条甜言蜜语。

axios({
       url: '/api/contract/' + id,
       method: 'put',
       data: {
             name: name
       }
       }) .then((response) => {
          this.$emit('fetchAll');
          swal({
               title: "Success!",
               icon: "success"
          });
       }) .catch(error => {
          this.errors = error.response.data.errors;
          swal({
             title: "Error",
             text: error.response.data.message,
             icon: "error"
       });
});

有回应:

403: You are not authorized to edit this contract.

network console

Laravel控制器中的错误处理:

if (Bouncer::cannot('contract-destroy'))
    abort('403', "You are not authorized to delete this contract");

即使请求中出现错误,也会弹出成功消息。

2 个答案:

答案 0 :(得分:0)

对于您的甜人,将密钥icon更改为type。否则,我认为默认情况下会显示成功消息。因此代码应阅读

axios({
       url: '/api/contract/' + id,
       method: 'put',
       data: {
             name: name
       }
       }) .then((response) => {
          this.$emit('fetchAll');
          swal({
               title: "Success!",
               type: "success"
          });
       }) .catch(error => {
          this.errors = error.response.data.errors;
          swal({
             title: "Error",
             text: error.response.data.message,
             type: "error"
       });
});

答案 1 :(得分:0)

我现在发现了问题,回调参数应定义为Object。我不知道为什么会出现问题,但现在已解决。

axios({
   url: '/api/contract/' + id,
   method: 'put',
   data: {
         name: name
   }
   }) .then(({data}) => { <-------instead of (response)
      this.$emit('fetchAll');
      swal({
           title: "Success!",
           icon: "success"
      });
   }) .catch(error => {
      this.errors = error.response.data.errors;
      swal({
         title: "Error",
         text: error.response.data.message,
         icon: "error"
   });

});