Cakephp REST API 消除了 .format 的必要性 [英] Cakephp REST API remove the necessity of .format
问题描述
我正在创建一个 REST api,它只会获取和返回 JSON 数据.
I am working on creating a REST api that will only get and return JSON data.
我遵循蛋糕指南,我的默认路线是这样的:
I'm following the cake guide and my default routes are like this:
GET /recipes.format
GET /recipes/123.format
POST /recipes.format
PUT /recipes/123.format
DELETE /recipes/123.format
POST /recipes/123.format
但是,我真的不喜欢使用.format"(在我的例子中是.json"),因为我只会接受 json.
However, I really dislike the necessity of using the ".format" (".json" in my case) since I will only ever be accepting json.
我觉得必须有办法消除这种必要性.我可以使用 .htaccess 来重写 URL,但我觉得必须有一种方法可以在某个蛋糕设置/配置文件中做到这一点.
I feel like there has to be a way to remove this necessity. I could use .htaccess to rewrite URLS, but I feel like there must be a way to do this in a cake setting / config file somewhere.
简而言之,我想成为 GET/recipes
并让它输出与 GET/recipes.json
相同的内容.
In short, I want to be abe to GET /recipes
and have it output the same thing as GET /recipes.json
would.
谢谢!
推荐答案
我假设您正在使用 RequestHandler
组件.一种方法是在您的控制器中对 extension 进行硬编码 beforeFilter()
回调:
I assume you are using the RequestHandler
component. One way would then be to hardcode the extension in your controllers beforeFilter()
callback:
public function beforeFilter()
{
parent::beforeFilter();
$this->RequestHandler->ext = 'json';
}
这样它就会始终使用 JSON 视图和适当的响应头,即使 扩展解析已启用,并且在 URL 中提供了非 .json 扩展.
That way it would always use the JSON View and appropriate response headers, even if extension parsing is enabled and a non-.json extension was supplied in the URL.
另一种选择是使用 RequestHandlerComponent::renderAs()
在您的单个控制器操作中:
Another option would be to use RequestHandlerComponent::renderAs()
in your individual controller actions:
public function index()
{
$this->RequestHandler->renderAs($this, 'json');
...
}
这会产生相同的效果,但您需要在所有操作中执行此操作,因此如果控制器的唯一目的是处理 REST 请求,您最好覆盖扩展程序.
That would have the same effect, but you would need to do this in all of your actions, so in case the controllers solely purpose is to handle REST requests, you are probably better off overriding the extension.
这篇关于Cakephp REST API 消除了 .format 的必要性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!