pathinfo(); // 判断是否为API请求(非index页面) $isApiRequest = $pathinfo !== 'crawler' && strpos($pathinfo, 'crawler/') === 0; if (empty($username)) { // 如果是API请求,返回JSON if ($isApiRequest || $request->isAjax()) { header('Content-Type: application/json; charset=utf-8'); return json([ 'code' => 0, 'msg' => '请先登录', ]); } // 否则跳转到登录页 return redirect('/login'); } return $next($request); } }