第一种方法:
第一步、编写 BaseRequest
首先我们需要构建一个 BaseRequest 来重写 IlluminateHttpRequest ,修改为默认优先使用 JSON 响应:
app/Http/Requests/BaseRequest.php
<?php namespace AppHttpRequests; use IlluminateHttpRequest; class BaseRequest extends Request { public function expectsJson() { return true; } public function wantsJson() { return true; } }
第二步、替换 BaseRequest
在 public/index.php 文件中,将 IllumiateHttpRequest 替换为我们的 BaseRequest,如下:
$response = $kernel->handle( $request = AppHttpRequestsBaseRequest::capture() );
第二种方法:
使用中间件
namespace AppHttpMiddleware; use Closure; class ForceJson { /** * Handle an incoming request. * * @param IlluminateHttpRequest $request * @param Closure $next * @return mixed */ public function handle($request, Closure $next) { $request->headers->set('accept', 'application/json'); return $next($request); } }
Kernel.php 加入
'force-json' => AppHttpMiddlewareForceJson::class,
修改 routes/api.php
Route::group(['middleware' => ['force-json', 'auth:api']], function () { // put your router });