【问题标题】:How to use API Routes in Laravel 5.3如何在 Laravel 5.3 中使用 API 路由
【发布时间】:2017-01-25 04:46:51
【问题描述】:

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

【问题讨论】:

标签: api laravel laravel-5.3


【解决方案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');
    });
}

【讨论】:

    【解决方案2】:

    你叫它

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

    如果您查看 app/Providers/RouteServiceProvider.php,您会看到默认情况下它会为 API 路由设置 api 前缀,当然您可以根据需要更改。

    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 你用的完全一样。从 URI 中删除 app 段。它应该看起来像localhost/api/user
    猜你喜欢
    • 2017-04-04
    • 2017-02-28
    • 2017-01-24
    • 2017-05-25
    • 2017-08-10
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    相关资源
    最近更新 更多