中间件直接 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
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
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年前 评论

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