Вопрос

I'm trying to migrate an existing web app to the Lithium framework.

If I POST JSON-encoded data to an URL and set the Content-Type header to application/json on the request, the POST'd data is automatically parsed and available in the controller (as $this->request->data). Hooray.

However, I need to support a client app which does not set the Content-Type header properly. In this case, the framework assumes it is URL-encoded form data and attempts to parse it as such.

Is there any way to override the request's Content-Type for a particular URL, in time for it to be parsed correctly?

Это было полезно?

Решение

Try the following in your bootstrap.php script. If the request data array only has one item in it, and that item can be decoded, the request data is replaced with the decoded json data.

use \lithium\action\Dispatcher;

Dispatcher::applyFilter('run', function($self, $params, $chain) {

    // Only check for JSON data for a certain URL
    if($params['request']->url == 'your/url/here') {

        // If the data array only has one element and the key can be decoded as
        // JSON data, replace the request data with the decoded JSON array
        if(count($params['request']->data) == 1) {
            $keys = array_keys($params['request']->data);
            $data = $keys[0];
            if(($data = json_decode($data, true)) != null) {
                $params['request']->data = $data;
            }
        }
    }

    return $chain->next($self, $params, $chain);

});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top