我在下面有路由文件
Route::group(['middleware' => ['auth:web', 'web'], 'prefix' => 'api/1.0'], function () {
Route::get('dashboard', 'DashboardController@index');
Route::get('site/{id}', 'SiteController@index');
});
当我没有登录,并试图参考url http://app.url/api/1.0/,是返回登录面板。我如何设置而不是登录面板,返回json数据(例如[message: forbidden])。我尝试在中间件设置,但larver崩溃了。谢谢你
您可以使用auth:api
中间件:
Route::group(['middleware' => ['auth:api'], 'prefix' => 'api/1.0'], function () {
Route::get('dashboard', 'DashboardController@index');
Route::get('site/{id}', 'SiteController@index');
});
所有异常由App'Exceptions'Handler
类处理。您可以编辑该类的render()
函数,使其返回JSON
响应:
public function render($request, Exception $exception)
{
if ($request->is('api/*');) {
return $this->renderRestException($request, $exception);
}
return parent::render($request, $exception);
}
在同一个文件中添加两个函数:
/**
* Render an exception into a response.
*
* @param 'Illuminate'Http'Request $request
* @param 'Exception $e
* @return 'Illuminate'Http'JsonResponse
*/
public function renderRestException(Request $request, Exception $e)
{
switch($e)
{
case ($e instanceof HttpResponseException):
return response()->json($e->getResponse()->getContent(), $e->getResponse()->getStatusCode());
case ($e instanceof ModelNotFoundException):
return response()->json($e->getMessage(), 404);
case ($e instanceof AuthenticationException):
return response()->json('Unauthorized', 401);
case ($e instanceof AuthorizationException):
return response()->json($e->getMessage(), 403);
default:
return $this->convertExceptionToJsonResponse($e);
}
}
/**
* Create a Symfony response for the given exception.
*
* @param 'Exception $e
* @return 'Illuminate'Http'JsonResponse
*/
protected function convertExceptionToJsonResponse(Exception $e)
{
$e = FlattenException::create($e);
return response()->json(array_get(SymfonyResponse::$statusTexts, $e->getStatusCode()), $e->getStatusCode());
}
记住要在类的顶部导入所有这些类:
use Exception;
use Illuminate'Http'Request;
use Illuminate'Auth'AuthenticationException;
use Illuminate'Auth'Access'AuthorizationException;
use Illuminate'Http'Exception'HttpResponseException;
use Symfony'Component'Debug'Exception'FlattenException;
use Illuminate'Database'Eloquent'ModelNotFoundException;
use Symfony'Component'HttpFoundation'Response as SymfonyResponse;