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

FRR*_*FRR 9 php rest android laravel

我有一个带控制器的RESTful API,它应该在我的Android应用程序被命中时返回JSON响应,当它被Web浏览器命中时应该返回"视图".我甚至不确定我是以正确的方式接近这一点.我正在使用Laravel,这就是我的控制器的样子

class TablesController extends BaseController {

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

        return Response::json($tables);
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要这样的东西

class TablesController扩展BaseController {

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

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

看看答案如何相互不同?

MAS*_*ASh 9

注意::这是供将来的观众使用的

我发现方便的方法是api对api调用使用前缀。在路由文件中使用

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

在以上方法中,我将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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 当您使用像 cloudflare 这样的服务时,您的答案非常有用。因为我注意到,当使用 ajax 发出 http 请求时,标头会被 cloudflare 更改,并且 Laravel 根据 Accept 标头中的值确定请求是否需要 json。使用 $request->is('api/*') 而不是 $request->expectsJson() 对我来说就像一个魅力。 (2认同)

Unn*_*wut 8

你可以Request::wantsJson()像这样使用:

if (Request::wantsJson()) {
    // return JSON-formatted response
} else {
    // return HTML response
}
Run Code Online (Sandbox Code Playgroud)

基本上Request::wantsJson(),它检查accept请求中的头是否为application/json并且基于此返回true或false.这意味着您需要确保您的客户端也发送"accept:application/json"标头.

请注意,我的答案不是确定"请求是来自REST API",而是检测客户端是否请求JSON响应.我的答案应该仍然是这样做的方法,因为使用REST API并不需要JSON响应.REST API可能会返回XML,HTML等.


参考Laravel的Illuminate\Http\Request:

/**
 * Determine if the current request is asking for JSON in return.
 *
 * @return bool
 */
public function wantsJson()
{
    $acceptable = $this->getAcceptableContentTypes();

    return isset($acceptable[0]) && $acceptable[0] == 'application/json';
}
Run Code Online (Sandbox Code Playgroud)