为所有路由添加JSON路由来处理后端请求


Add JSON routes for all routes to handle backend requests

我正在使用Laravel 5.1,并正在构建一个可以被视为JSON或HTML的服务。像reddit这样的网站已经采用了这种方法。
正常视图:http://www.reddit.com/r/soccer
JSON视图:http://www.reddit.com/r/soccer.json

正如您所看到的,他们只是将.json添加到URL中,用户就能够以HTML或JSON的形式看到完全相同的内容。

我现在想在Laravel中复制相同的内容,但是我遇到了多个问题。

方法1 -可选参数

我尝试的第一件事是在我所有的路由中添加可选参数

Route::get('/{type?}', 'HomeController@index');
Route::get('pages/{type?}', 'PageController@index');

然而,我在这里面临的问题是,所有路由都被HomeController捕获,这意味着/pages/?type=json/pages?type=json被重定向到HomeController。

方法2 -使用命名空间进行路由分组

接下来,我尝试添加路由分组与命名空间,以分离后端和前端

Route::get('pages', 'PageController@index');
Route::group(['prefix' => 'json', 'namespace' => 'Backend'], function(){
    Route::get('pages', 'PageController@index');
});

然而,这也不起作用。当使用api作为前缀时,它确实有效,但我想要的是,我可以将.json添加到每个URL并获得json结果。我如何在Laravel中实现这一点?

您可以在参数上应用正则表达式,以避免出现HomeController@index:

Route::get('/pages{type?}', 'PageController@index'->where('type', ''.json'));

这样,只有当它等于.json时,它的类型才会匹配。

然后,要在控制器中访问它:

class PageController {
  public function index($type = null) {
    dd($type);
  }
}

,转到/pages.json