小编典典

如何在 REST api 中确定请求的来源

php

我有一个带有控制器的 RESTful API,当它被我的 android 应用程序点击时,它应该返回一个 JSON 响应,当它被 web 浏览器点击时,它应该返回一个“视图”。我什至不确定我是否以正确的方式接近这一点。我正在使用 Laravel,这就是我的控制器的样子

class TablesController extends BaseController {

    public function index()
    {
        $tables  = Table::all();

        return Response::json($tables);
    }
}

我需要这样的东西

class TablesController extends BaseController {

    public function index()
    {
        $tables  = Table::all();

        if(beingCalledFromWebBrowser){
            return View::make('table.index')->with('tables', $tables);
        }else{ //Android 
            return Response::json($tables);
        }
    }

看看响应之间有何不同?


阅读 62

收藏
2022-07-25

共1个答案

小编典典

注意::这是给未来的观众的

我发现使用apiapi 调用前缀很方便的方法。在路由文件中使用

Route::group('prefix'=>'api',function(){
    //handle requests by assigning controller methods here for example
    Route::get('posts', 'Api\Post\PostController@index');
}

在上述方法中,我将 api 调用和 Web 用户的控制器分开。但是如果你想使用同一个控制器那么Laravel Request有一个方便的方法。您可以在控制器中识别前缀。

public function index(Request $request)
{
    if( $request->is('api/*')){
        //write your logic for api call
        $user = $this->getApiUser();
    }else{
        //write your logic for web call
        $user = $this->getWebUser();
    }
}

is方法允许您验证传入请求 URI 是否与给定模式匹配。使用此方法时,您可以使用该\*字符作为通配符。

2022-07-25