如何在 Laravel 5.3中使用 API 路由

在 Laravel 5.3中,API 路由被移动到 API.php 文件中。但是如何在 api.php 文件中调用路由呢?我试图创建一个像这样的路线:

Route::get('/test',function(){
return "ok";
});

我尝试了以下 URL,但都返回了 NotFoundHttpException 异常:

  • http://localhost:8080/test/public/test
  • http://localhost:8080/test/public/api/test

如何调用这个 API 路由?

112239 次浏览

You call it by

http://localhost:8080/api/test
^^^

If you look in app/Providers/RouteServiceProvider.php you'd see that by default it sets the api prefix for API routes, which you can change of course if you want to.

protected function mapApiRoutes()
{
Route::group([
'middleware' => 'api',
'namespace' => $this->namespace,
'prefix' => 'api',
], function ($router) {
require base_path('routes/api.php');
});
}

routes/api.php

Route::get('/test', function () {
return response('Test API', 200)
->header('Content-Type', 'application/json');
});

Mapping is defined in service provider App\Providers\RouteServiceProvider

protected function mapApiRoutes(){
Route::group([
'middleware' => ['api', 'auth:api'],
'namespace' => $this->namespace,
'prefix' => 'api',
], function ($router) {
require base_path('routes/api.php');
});
}