鍍金池/ 問答/PHP  GO/ 怎么讓自定義中間件對ajax請求返回指定狀態(tài)碼和相應(yīng)信息?

怎么讓自定義中間件對ajax請求返回指定狀態(tài)碼和相應(yīng)信息?

就像laravel自帶auth中間件一樣,如果是通過web訪問,未認(rèn)證的話會跳轉(zhuǎn)到登陸頁面,如果通過ajax訪問,則會返回一個401狀態(tài)碼,并返回一條json消息:{"message":"Unauthenticated."}

auth中間件的源碼:

public function handle($request, Closure $next, ...$guards)
    {
        $this->authenticate($guards);


        return $next($request);
    }

    
protected function authenticate(array $guards)
{
    if (empty($guards)) {
        return $this->auth->authenticate();
    }

    foreach ($guards as $guard) {
        if ($this->auth->guard($guard)->check()) {
            return $this->auth->shouldUse($guard);
        }
    }

    throw new AuthenticationException('Unauthenticated.', $guards);
}

如果說message是由異常返回的,那狀態(tài)碼是在哪里設(shè)定的?

回答
編輯回答
過客

app\Exceptions\Handler.php

 /**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        return redirect()->guest(route('login'));
    }
2017年4月23日 09:25