Axios响应未定义,尽管浏览器网络选项卡显示响应

lp0sw83n  于 8个月前  发布在  iOS
关注(0)|答案(2)|浏览(70)

我使用Laravel和Vue 3与axios来处理用户输入和保存数据到数据库。如果有验证错误,那么我想向用户显示一个吐司错误。
由于某种原因,如果Laravels验证失败,axios put函数的响应是未定义的。我已经尝试了我在网上找到的所有其他修复方法,但仍然没有定义。
我的axios示例:

const instance = axios.create({
    baseURL: import.meta.env.VITE_API_BACKEND_URL,
    withCredentials: true,
    headers: {
        Accept: `application/json`,
    },
});

字符串
调用Laravel的函数(API是上面创建的axios示例):

async confirmOrder(order: splicingPurchaseOrderType) {
   Api.put(`/splicing_purchase_orders/${order.id}`, {
      ...order,
   }).then((response: any) => {
      console.log(response);
   });


在Laravel中调用的函数:

public function put(SplicingPurchaseOrder $splicingPurchaseOrder, Request $request): JsonResponse
{
   $validated = $request->validate([
      'pallets' => 'required|numeric',
      'quality_id' => 'required|exists:App\Domain\Quality\Models\Quality,external_id',
      'specie_id' => 'required|exists:App\Domain\Specie\Models\Specie,external_id',
   ]);


下面是浏览器开发工具的实际响应截图:Screenshot of dev tools network tab
我错过了什么?
我可以用if(!响应)并显示一些通用错误,但这似乎不正确,我已经显示Laravel验证错误之前刚刚好.但目前我不明白发生了什么,应该是一个微不足道的任务,但我失败了.
我读到其他人一直在混合await和.then()在一起,这导致了问题,但这似乎不是我面临的问题。尝试const response = await Api. put.
尝试在Laravel的try catch块中 Package 验证并自己编写返回,仍然是同样的问题。
一定很简单,我只是没看出来。

iibxawm4

iibxawm41#

没关系,找到问题了。
我也有拦截器,以处理NProgress行为。
Interceptor on response看起来像这样:

instance.interceptors.response.use(
    (response) => {
        callCount.value--;
        return response;
    },
    (error) => {
        callCount.value--;
    }
);

字符串
错误在这里消失了。添加了return,使拦截器看起来像这样:

instance.interceptors.response.use(
    (response) => {
        callCount.value--;
        return response;
    },
    (error) => {
        callCount.value--;
        return Promise.reject(error);
    }
);


现在我从Axios获得了预期的行为。

yizd12fk

yizd12fk2#

Axios方法返回一个Promise,只有当响应的状态码在200-299之间(包括200和299)时,Promise才会被解析。对于任何其他状态码,Promise都将被拒绝。
在本例中,由于状态代码为422,因此您可以使用以下代码段中的任何一个来处理错误:
使用async/await

async confirmOrder(order: splicingPurchaseOrderType) {
  try {
    const res = await Api.put(`/splicing_purchase_orders/${order.id}`, {
      ...order,
    });
    console.log(res.data); // Success response
  } catch (error) {
    console.log(error.response.data); // Error response
  }
}

字符串
使用Promise.then/catch

confirmOrder(order: splicingPurchaseOrderType) {
  Api.put(`/splicing_purchase_orders/${order.id}`, {
    ...order,
  })
    .then((res) => console.log(res.data)) // Success response
    .catch((error) => console.log(error.response.data)); // Error response
}

相关问题