How to use API Routes in Laravel 5.3

我只是一个虾纸丫 提交于 2019-12-17 17:52:59

问题


In Laravel 5.3 API routes were moved into the api.php file. But how can I call a route in api.php file? I tried to create a route like this:

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

I tried the following URLs but both returned the NotFoundHttpException exception:

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

How can I call this API route?


回答1:


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');
    });
}



回答2:


If you want to customize this or add your own separate routes files, check out App\Providers\RouteServiceProvider for inspiration

https://mattstauffer.co/blog/routing-changes-in-laravel-5-3




回答3:


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');
    });
}


来源:https://stackoverflow.com/questions/39540236/how-to-use-api-routes-in-laravel-5-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!