dpql57753 2018-03-21 02:28
浏览 281
已采纳

ajax(api route)上的Laravel 5.6验证器返回200而不是422

I am posting on Postman to my api route (in api.php) and when the data fails in validation, it returns me the errors in 200 response under this:

enter image description here

The above response is when I try:

{
    $valid = validator($request->only('email', 'password'), [
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6',
    ]);

    if ($valid->fails()) {
        $jsonError=response()->json($valid->errors()->all(), 400);
        return \Response::json($jsonError);
    }
}

However, when I try the one in the documentation like below, it returns me to the view (laravel welcome page), something like return back()

 $request->validate([
     'email' => 'required|string|email|max:255|unique:users',
     'password' => 'required|string|min:6',
 ]);

And the data I post is:

email: ''
password: ''

// also tried with and without header
Content-Type: application/json
  • 写回答

2条回答 默认 最新

  • douping6871 2018-03-21 02:52
    关注

    This code is problematic.

    $jsonError=response()->json($valid->errors()->all(), 400);
    return \Response::json($jsonError);
    

    $jsonError is already a JSONResponse object, then you've encapsulated it again inside a JSONReponse object.

    The json method creates a new JSONResponse object, here is the underlying code.

    public function json($data = [], $status = 200, array $headers = [], $options = 0)
    {
        return new JsonResponse($data, $status, $headers, $options);
    }
    

    So, when you've pass $jsonError here, it was the $data argument. Now, $status argument has a default value of 200, but you DIDN'T pass any, as per your code:

    return \Response::json($jsonError);
    //                               ^-- yeah, no $status argument here!
    

    So it is correct that you will have a 200 response.

    To fix your issue, just return the first JSONResponse object you've created.

    return response()->json($valid->errors()->all(), 400);
    

    If you still want to stick with your current code, then do this. But this is pointless.

    $jsonError=response()->json($valid->errors()->all(), 400);
    return \Response::json($jsonError, 400);
    

    Also, response()->json() is just the same as Response::json() :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!