如何在Laravel 5.3中使用API​​路由


93

在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路由?


Answers:


173

你叫它

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

如果您app/Providers/RouteServiceProvider.php查看,默认情况下它将设置apiAPI路由的前缀,当然您可以根据需要进行更改。

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

知道如何在laravel 5.4中调用它吗?默认的api路由:Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); }); 我尝试了localhost / app / api / user但没有用
utdev

@utdev您使用完全相同。app从您的URI中删除细分。它应该遵循localhost/api/user
peterm '17


1

路线/api.php

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

映射在服务提供者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');
    });
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.