第一种方法:
第一步、编写 BaseRequest
首先我们需要构建一个 BaseRequest 来重写 Illuminate\Http\Request ,修改为默认优先使用 JSON 响应:app/Http/Requests/BaseRequest.php
第二步、替换 BaseRequest
在 public/index.php 文件中,将 \Illumiate\Http\Request 替换为我们的 BaseRequest,如下:$response = $kernel->handle( $request = \App\Http\Requests\BaseRequest::capture());
第二种方法:
使用中间件
namespace App\Http\Middleware;use Closure;class ForceJson{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $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' => \App\Http\Middleware\ForceJson::class,
修改 routes/api.php
Route::group(['middleware' => ['force-json', 'auth:api']], function () { // put your router});