简体   繁体   English

CakePHP Routing JSON响应

[英]CakePHP Routing json response

I am currently using RestApi plugin for CakePHP 3 and I want to be able to append the extension .json to URL, like so: 我目前使用RESTAPI插件CakePHP的3 ,我希望能够扩展追加.json到URL,就像这样:

domain.com/api/search/abc.json

Following CakePHP's docs about creating RESTful routes I was able to use the extension without throwing an error. 在CakePHP关于创建RESTful路由的文档之后,我能够使用扩展而不会引发错误。

I have this on my routes.php (edit to add the whole code) 我在routes.php上有这个(编辑以添加整个代码)

use Cake\Core\Plugin;
use Cake\Routing\RouteBuilder;
use Cake\Routing\Router;
use Cake\Routing\Route\DashedRoute;

Router::defaultRouteClass(DashedRoute::class);

Router::scope('/', function (RouteBuilder $routes) {
    $routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);

    $routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);

    $routes->fallbacks(DashedRoute::class);
});

Plugin::routes();
Router::scope('/', function ($routes) {
    $routes->extensions(['json']);
});

In my controller, if I do this: 在我的控制器中,如果我这样做:

public function search($term=''){
    $this->httpStatusCode = 200;
    $this->apiResponse['term'] = $term;
}

The response is: 响应为:

{
    "status": "OK",
    "result": {
        "term": "abc.json" # Notice the .json
    }
}

So, I get abc.json , when I want abc . 所以,当我想要abc时,我得到了abc.json

Am I doing something wrong? 难道我做错了什么? Or am I supposed to strip the .json from $term ? 或者我应该从$term剥离.json

While reusing existing scopes will merge the connected routes to the same routes collection, calls to RouteBuilder::extensions() will generally not affect previously connected routes, and they also do not affect reused/reopened scopes. 重用现有作用域会将合并的路由合并到相同的路由集合中,但对RouteBuilder::extensions()调用通常不会影响以前连接的路由,也不会影响重用/重新打开的作用域。

Quote from the docs: 从文档引用:

Future routes connected in through this builder will have the connected extensions applied. 通过此构建器连接的将来路由将应用连接的扩展。 However, setting extensions does not modify existing routes. 但是,设置扩展名不会修改现有路由。

API > \\Cake\\Routing\\RouteBuilder::extensions() API> \\ Cake \\ Routing \\ RouteBuilder :: extensions()

You should add the extensions() call in the existing routing scope, so that it affects the routes that are being connected in there after the extensions() call. 您应该在现有的路由范围内添加extensions()调用,以便它影响在extensions()调用之后在那里连接的路由。

See also 也可以看看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM