使用 CakePHP 3 和 Crud 插件强制 JSON 格式

Force JSON format using CakePHP 3 and Crud plugin

我已经按照How to build a CakePHP 3 REST API tutorial to create REST API. Tutorial describes case when requests are made with extensions (json/xml) to set response format. Plugin CRUD for CakePHP使用了

我想在不使用 .json 扩展名 的情况下强制使用 JSON 响应格式 。我的请求出现 MissingRouteException。

我尝试了什么

Router::prefix('api', function ($routes) {
    //$routes->extensions(['json', 'xml']);
    $routes->resources('Cocktails');
});

加上

#1

$this->RequestHandler->ext = 'json' 变成 AppController::beforeFilter()

#2

$this->RequestHandler->renderAs($this, 'json'); 变成 AppController::beforeFilter()

但这试图使用来自 Template/Api/Coctails/json

的模板

我希望它的行为与带扩展名的情况完全一样。

谢谢

使用 a proper HTTP accept header Accept: application/json 请求您的数据,然后 RequestHandler 应该会拾取它。

The Accept header is used by HTTP clients to tell the server what content types they'll accept. The server will then send back a response, which will include a Content-Type header telling the client what the content type of the returned content actually is.

However, as you may have noticed, HTTP requests can also contain Content-Type headers. Why? Well, think about POST or PUT requests. With those request types, the client is actually sending a bunch of data to the server as part of the request, and the Content-Type header tells the server what the data actually is (and thus determines how the server will parse it).

In particular, for a typical POST request resulting from an HTML form submission, the Content-Type of the request will normally be either application/x-www-form-urlencoded or multipart/form-data.