如何在 Laravel 5.3 中使用 API 路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39540236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:31:26  来源:igfitidea点击:

How to use API Routes in Laravel 5.3

apilaravellaravel-5.3

提问by gw0

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:

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

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

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

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

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

How can I call this API route?

如何调用此 API 路由?

回答by peterm

You call it by

你叫它

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

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

如果您查看,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');
    });
}

回答by macieks

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

如果你想自定义这个或添加你自己单独的路由文件,请查看 App\Providers\RouteServiceProvider 以获得灵感

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

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

回答by Chandrakant Ganji

routes/api.php

路线/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

映射定义在服务提供者 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');
    });
}