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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24590590/
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-14 09:46:47  来源:igfitidea点击:

How to determine where a request is coming from in a REST api

phpandroidrestlaravel

提问by FRR

I have an RESTful API with controllers that should return a JSON response when is being hit by my android application and a "view" when it's being hit by a web browser. I'm not even sure I'm approaching this the right way. I'm using Laravel and this is what my controller looks like

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

class TablesController extends BaseController {

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

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

I need something like this

我需要这样的东西

class TablesController extends BaseController {

类 TablesController 扩展 BaseController {

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

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

See how the responses differ from each other?

看看反应之间有何不同?

回答by Unnawut

You can use Request::wantsJson()like this:

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

if (Request::wantsJson()) {
    // return JSON-formatted response
} else {
    // return HTML response
}

Basically what Request::wantsJson()does is that it checks whether the acceptheader in the request is application/jsonand return true or false based on that. That means you'll need to make sure your client sends an "accept: application/json" header too.

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

Note that my answer here does not determine whether "a request is coming from a REST API", but rather detects if the client requests for a JSON response. My answer should still be the way to do it though, because using REST API does not necessary means requiring JSON response. REST API may return XML, HTML, etc.

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



Reference to Laravel's Illuminate\Http\Request:

参考 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';
}

回答by MASh

Note::This is for future viewers

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

The approach I found convenient is to using a prefix apifor api calls. In the route file use

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

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

In the above approach, I separate controllers for api call and web users. But if you want to use the same controller then laravel Requesthas a convenient way. You can identify the prefix within your controller.

在上述方法中,我将 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();
    }
}

The is method allows you to verify that the incoming request URI matches a given pattern. You may use the * character as a wildcard when utilizing this method.

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

回答by Tarmizi Sanusi

You can use

您可以使用

if ($request->wantsJson()) {
     // enter code heree
}