中间件直接 return JSON 串导致异常

在中间件的逻辑使用中,直接return json

 public function handle($request, Closure $next)
    {
        if ($request->age <= 200) {
            $arr = [
                  'code' => 4,
                  'msg' => 'age <200'
                ];
            return json_encode($arr);//这里是导致异常的根源***
        }

        return $next($request);
    }

}

以上代码描述 备注*** 标注行为问题的根源
导致异常

ErrorException (E_NOTICE)
Trying to get property 'headers' of non-object

报错位置:laravel_5.8\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php
报错位置为以下:*** 位置标注

     * Add the CSRF token to the response cookies.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Symfony\Component\HttpFoundation\Response  $response
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function addCookieToResponse($request, $response)
    {
        $config = config('session');

        $response->headers->setCookie(  //***************//
            new Cookie(
                'XSRF-TOKEN', $request->session()->token(), $this->availableAt(60 * $config['lifetime']),
                $config['path'], $config['domain'], $config['secure'], false, false, $config['same_site'] ?? null
            )
        );

        return $response;
    }
Phor
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
leo
最佳答案

在中间件里应该返回一个 Response 对象,return response()->json($arr);

4年前 评论
free-andy 3年前
讨论数量: 3
leo

在中间件里应该返回一个 Response 对象,return response()->json($arr);

4年前 评论
free-andy 3年前
Phor

感谢 老铁 解决了 :+1:

4年前 评论

非常感谢,困扰我几天了

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!