【问题标题】:I'm not getting the errors back using axios我没有使用 axios 恢复错误
【发布时间】:2022-10-14 15:20:11
【问题描述】:

即使我使用 axios 使用了 validate() 方法,我也没有收到错误。

这是我的控制器,

public function store(Request $request)
{
      $fields = $request->validate([
         'product_name' => 'required',
        'product_cost' => 'required | integer',
        'product_selling' => 'required | integer',
        'product_stock' => 'required | integer',
 ]);

Product::create([
    'name' => $fields['product_name'],
    'cost' => $fields['product_cost'],
    'selling' => $fields['product_selling'],
    'stock' => $fields['product_stock'],
]); }

这是我的 Vue 文件

    const productState = reactive({
        product_name: "",
        product_cost: "",
        product_markup: "",
        markup_type: "Markup by price",
        product_selling: "",
        product_stock: "",
        returned_errors: [],
    });

   axios .post("api/products", productState)
    .then((response) => {
        console.log(response);
    })
    .catch((error) => console.log(error.response.data.errors));

即使它有错误,它仍然会返回响应。

【问题讨论】:

  • 首先,您应该了解$request->validatethis 如何抛出验证异常及其格式,以及 laravel 如何确定您的请求是 API 调用。您应该发送 Accept: application/json 标头,以便 laravel 知道您想要返回 API 响应。
  • @AnujShrestha 不起作用兄弟我试过:(
  • 好的,我将发布一个适用于您的代码的答案

标签: laravel vue.js vuejs2 axios try-catch


【解决方案1】:
   try {
        $fields = $request->validate([
            'product_name' => 'required',
            'product_cost' => 'required | integer',
            'product_selling' => 'required | integer',
            'product_stock' => 'required | integer',]);
    } catch (ValidationException $ex) {
        return response()->json(['errors' =>$ex->errors()], 422); //what ever error format that you desire
    }

如果您正在发送 API 请求,您应该 try catch $request->validate 并发回自定义响应。

但我不建议使用 $request->validateAPI 请求,您可以使用 Form Request 或 Validator::make() 以获得更大的 api 请求灵活性,并且您也可以在 Handler.php 文件中捕获验证异常并在那里处理它。

已经发布了很多文章,因此请尝试研究“Larvel Validation for API requests”。 (我不会链接到具体的文章,你可以在 Youtube 视频中找到博客文章中的文章)

它将帮助您从整体上理解 Laravel 验证过程。

【讨论】:

    【解决方案2】:

    您是否尝试过:

    error.response.data.error
    

    或者只是记录错误并查看结构是什么

    【讨论】:

    • 但是错误没有显示
    【解决方案3】:

    Axios 中返回的错误并不总是具有error.response 属性。您可能应该将错误处理构造为in this example in the Axios docs

    希望这可以帮助。

    【讨论】:

    • 但是错误没有显示
    猜你喜欢
    • 1970-01-01
    • 2018-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    相关资源
    最近更新 更多