用户认证失败不想跳转页面,想返回json数据

Laravel

用户认失败后,这里直接跳转页面了,我现在想返回json该怎么办

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
最佳答案
  1. http请求的时候添加header Accept:json
  2. file
3年前 评论
讨论数量: 6

从权限验证那直接跳走了,没有走到这个方法

3年前 评论
  1. http请求的时候添加header Accept:json
  2. file
3年前 评论
porygonCN

在ExceptionHandle中改写处理逻辑或者在App\Http\MiddlewareAuthenticate下重写unauthenticated方法抛出自定义错误并自定义处理逻辑。 原因:在继承的中间件中有unauthenticated方法如下:

    /**
     * Handle an unauthenticated user.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  array  $guards
     * @return void
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    protected function unauthenticated($request, array $guards)
    {
        throw new AuthenticationException(
            'Unauthenticated.',
            $guards,
            $this->redirectTo($request)
        );
    }
3年前 评论

若是 api 请求请加上下面请求头,中间件除了json请求才会跳

Content-Type:application/json
X-Requested-With:XMLHttpRequest

若是web请求

    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
//            return route('login');
            return response()->json([
                'foo'=>'bar'
            ]);
        }
    }
3年前 评论

app/Exceptions/Handler.php

public function render($request, Exception $exception)
{
    if ($exception instanceof \Illuminate\Auth\Access\AuthorizationException) {
        return response()->json(['message' => $exception->getMessage()], 401);
    }

    return parent::render($request, $exception);
}
3年前 评论

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