如何确定REST API中的请求来自何处 [英] How to determine where a request is coming from in a REST api
问题描述
我有一个带控制器的RESTful API,当被我的android应用程序击中时应返回JSON响应,当被网络浏览器击中时应返回视图".我什至不确定我是否正在采用正确的方法.我正在使用Laravel,这就是我的控制器的样子
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
class TablesController extends BaseController {
public function index()
{
$tables = Table::all();
return Response::json($tables);
}
}
我需要这样的东西
TablesController类扩展了BaseController {
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);
}
}
看看响应之间有何不同?
See how the responses differ from each other?
推荐答案
您可以像这样使用 Request :: wantsJson()
:
if (Request::wantsJson()) {
// return JSON-formatted response
} else {
// return HTML response
}
基本上, Request :: wantsJson()
的作用是检查请求中的 accept
标头是否为 application/json
并返回基于此,对或错.这意味着您需要确保客户端也发送"accept:application/json"标头.
Basically what Request::wantsJson()
does is that it checks whether the accept
header in the request is application/json
and return true or false based on that. That means you'll need to make sure your client sends an "accept: application/json" header too.
请注意,我在这里的答案不会确定请求是否来自REST API",而是会检测客户端是否请求JSON响应.我的答案仍然应该是这样做的方法,因为使用REST API并不一定意味着需要JSON响应.REST API可能会返回XML,HTML等.
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.
参考Laravel的 Illuminate \ Http \ Request:
Reference to Laravel's 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';
}
这篇关于如何确定REST API中的请求来自何处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!